Using Eloquent whereBetween With Dates In Laravel

Eloquent has many criteria extendable methods that help with day to day queries. In this tutorial, we will look at the usual ‘between’ keyword and how it is used within eloquent rather than raw SQL.

Let’s assume that we have a students database table with student records. One of it’s fields is enrolled which is of datetime format.

In addition, let’s assume we want to query the records to return any students that are between two given date times.

If we were to use a raw SQL query, it would look something like this –

select * from students where enrolled between '2020-06-01 00:00:00' and '2020-06-01 00:00:00'

So how do we replicate this with Eloquent? Well, the answer is, using the whereBetween() method within our eloquent query.

whereBetween() offers 2 parameters, the first the column key that we are applying the criteria to. The second is a string array of datetime.

Let’s see this in action in some Laravel Eloquent code.

                                         //Col key    DateTimeFrom            DateTimeTo 
$students = Student::all()->whereBetween('enrolled', ['2020-06-01 00:00:00', '2020-0-28 00:00:00']);

After this eloquent query is executed, a ‘between’ criteria will applied to the entire query, utilising the date times passed in as parameters onto the enrolled column.

 

Leave a Reply