Saturday, February 19, 2022

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

Issue

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();

Solution

There are date helpers available in the query builder:

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


Answered By - Martin Bean

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.