28

With MySQL, I can use the YEAR() function like this to filter by the year of a date field in a WHERE clause:

SELECT noworkorder FROM workorders WHERE YEAR(date)=2015;

In Laravel, I can of course achieve the same thing with a raw expression:

$data = DB::table('workorders')
       ->select('noworkorder')
       ->where(DB::raw('YEAR(date)=2015'))
       ->orderby('noworkorder', 'desc')
       ->get();

But is there a way to do this without raw expressions?

0

1 Answer 1

42

The query builder has a whereYear method:

$data = DB::table('workorders')
   ->select('noworkorder')
   ->whereYear('date', '=', 2015)
   ->orderby('noworkorder', 'desc')
   ->get();
1
  • There is any way to apply ->whereYear for all application quires, i mean if I want to put specific year on session to get only records created on this year for all models? Nov 23, 2016 at 23:57

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.