Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all records for current year?

How to get all articles for current year?

Articles::all()->where('created_at',$current_year);
like image 352
None Avatar asked Dec 26 '16 11:12

None


People also ask

How do I get the current year in SQL?

MySQL YEAR() Function The YEAR() function returns the year part for a given date (a number from 1000 to 9999).

How can I get last 12 months data in SQL?

mysql> select * from users where date_joined> now() - INTERVAL 12 month; In the above query, we use system function now() to get current datetime. Then we use INTERVAL clause to filter those records where order_date falls after an interval of 12 months before present datetime. That's it!

How do I get this year data in MySQL?

Use the YEAR() function to retrieve the year value from a date/datetime/timestamp column in MySQL. This function takes only one argument – a date or date and time. This can be the name of a date/datetime/timestamp column or an expression returning one of those data types.


2 Answers

You can do this:

Articles::whereBetween('created_at', [
    Carbon::now()->startOfYear(),
    Carbon::now()->endOfYear(),
]);

Another way is to use whereYear() as in @xhulio answer. But I'd recommend you to use this code instead as it's more readable:

Articles::whereYear('created_at', date('Y'))->get();
like image 97
Alexey Mezenin Avatar answered Sep 23 '22 20:09

Alexey Mezenin


Try the following query

Articles::whereYear('created_at', '=', Carbon::parse($date)->format('Y'))->get();

Laravel has the helper functions whereDate, whereDay, whereMonth and whereYear to better deal with datetime queries.

like image 27
xhulio Avatar answered Sep 21 '22 20:09

xhulio