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

My problem is that I want to get data form the database table from the created_at attributes as per year and month only. The code I have tried is:

$post= Mjblog::select(DB::raw('YEAR(created_at) year, MONTH(created_at) month'));
$posts_by_y_m = $post->where('created_at',$post)->get();

Answers


There are date helpers available in the query builder:

$post = Mjblog::whereYear('created_at', '=', $year)
              ->whereMonth('created_at', '=', $month)
              ->get();

If you want to get the year and month from a single instance of Mjblog you can access them like this:

$year = $post->created_at->year;
$month = $post->created_at->month;

Read more about Carbon\Carbon getters documentation.


Need Your Help

Stack Overflow on social networks (LinkedIn, Facebook, hi5, Orkut)

discussion stack-overflow social-networking

We now have groups for promoting Stack Overflow on some social networking sites. They are quasi-official.

"Origin null is not allowed by Access-Control-Allow-Origin" in Chrome. Why?

javascript google-chrome xmlhttprequest cross-domain

I am working on some Javascript to run locally on my PC. I am using a jQuery CSV plugin (http://plugins.jquery.com/project/csv) to load load a csv file into javascript arrays. The script is simple:...