Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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(); 
like image 796
Pawan Dongol Avatar asked Sep 29 '15 09:09

Pawan Dongol


People also ask

How to get month and year from created_ at in laravel?

You can use ->whereMonth('created_at', $month) also. Both will work.

How can we get data from database between two dates in laravel?

Try to do something like this: $date1 = Carbon::today()->toDateString(); $date2 = Carbon::today()->toDateString(); $myModel = MyModel::find(1); $myModel->whereBetween('created_at', [$date1, $date2]); $myModel->get();

How do I get my last month record from laravel?

Laravel Get Last Month records Use the below laravel eloquent query to get the last month records from the database table. User::whereMonth('created_at', '=', Carbon::now()->subMonth()->month)->get(['name','created_at']); This query uses laravel method whereMonth() and get().


1 Answers

There are date helpers available in the query builder:

$post = Mjblog::whereYear('created_at', '=', $year)               ->whereMonth('created_at', '=', $month)               ->get(); 
like image 123
Martin Bean Avatar answered Oct 10 '22 14:10

Martin Bean