How to select year and month from the created_at attributes of database table in laravel 5.1?

In Laravel 5.1, you can use the selectRaw method to select the year and month from the created_at attribute of a database table. Here's an example of how to do this in a query:

<?php

$results = DB::table('table_name')
  ->selectRaw('YEAR(created_at) as year, MONTH(created_at) as month')
  ->get();

The selectRaw method allows you to include raw expressions in the select statement, which in this case are the YEAR() and MONTH() functions that are used to extract the year and month from the created_at attribute. The as keyword is used to alias the extracted values as year and month respectively.

Watch a course Learn object oriented PHP

You can also use GROUP BY clause to group the data by year and month,

<?php

$results = DB::table('table_name')
  ->selectRaw('YEAR(created_at) as year, MONTH(created_at) as month, count(*) as total')
  ->groupBy('year', 'month')
  ->get();

The above query will group the data by year and month and it will also return total count of each group.