Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL YEAR() equivalent in Laravel query builder

Tags:

php

mysql

laravel

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?

like image 472
Dadan Hamdani Avatar asked Nov 05 '15 00:11

Dadan Hamdani


People also ask

How can we get data between two dates using query 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(); Of course, you will need to change the dates.

What is the difference between eloquent and query builder in laravel?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM. In my case, I use ELoquent ORM in an application with tables that will hold less than 17500 entries.

What is query builder in laravel with example?

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems.


1 Answers

The query builder has a whereYear method:

$data = DB::table('workorders')
   ->select('noworkorder')
   ->whereYear('date', '=', 2015)
   ->orderby('noworkorder', 'desc')
   ->get();
like image 65
Thomas Kim Avatar answered Oct 12 '22 06:10

Thomas Kim