Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.

The post Using Eloquent whereBetween With Dates In Laravel appeared first on Code Wall.



This post first appeared on Code Wall - Web Development & Programming, please read the originial post: here

Share the post

Using Eloquent whereBetween With Dates In Laravel

×

Subscribe to Code Wall - Web Development & Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×