Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Select records in specific year

I'm new to Laravel and struggling to identify how I can select all records created in 2015 using the created_at field provided by the timestamp.

The model I am using is Blog:

$posts = Blog::latest()->get();

Example date in database:

2015-01-25 12:53:27

Could anyone shed some light?

Thanks!

like image 549
Paolo Resteghini Avatar asked Nov 29 '22 01:11

Paolo Resteghini


2 Answers

Just for completition. There is a Laravel method for it.

Blog::whereYear('created_at', 2017)->get();

See where clause, subsection whereDate / whereMonth / whereDay / whereYear

like image 199
Ronon Avatar answered Dec 23 '22 20:12

Ronon


You can do it like that: $posts = Blog::where( DB::raw('YEAR(created_at)'), '=', '2015' )->get();

Here you can get year from created_at field with YEAR function, then compare with your date.

like image 20
mcklayin Avatar answered Dec 23 '22 20:12

mcklayin