Dadan Hamdani Dadan Hamdani - 3 months ago 14
MySQL Question

MySQL YEAR() equivalent in Laravel query builder

With MySQL, I can use the

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?

Answer

The query builder has a whereYear method:

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