Multiple Where Clauses Using Laravel

  • January 19, 2018

Welcome to the incredibly popular Easy Laravel 5 companion blog. To celebrate the new edition's release (updated for Laravel 5.5!) use the discount code easteregg to receive 20% off the book or book/video package! » Buy the book

Laravel's powerful Eloquent ORM offers a number of different ways to query your database. Using the HackerPair project as an example, suppose you wanted to retrieve a specific record and know the record's ID. To retrieve it you can use the find method:

$event = Event::find(42);

But what if you wanted to search the events table using criteria other than the primary key? For instance if you wanted to retrieve all events associated with the city Miami, then you could use a where condition:

$events = Event::where('city', 'Miami')->get();

This would translate to the following SQL:

SELECT * FROM events WHERE city = 'Miami';

It's possible to chain multiple where clauses together to create even more exacting queries:

$events = Event::where('city', 'Miami')->where('max_attendees', 5)->get();

This translates to the following SQL:

SELECT * FROM events WHERE city = 'Miami' AND max_attendees = 5;

Other variations of the where method are available to further customize queries. For instance the whereBetween method can be used to retrieve records in which a particular column contains an integer falling between two other integers:

$events = Event::where('city', 'Miami')->whereBetween('max_attendees', [1,3])->get()

This translates to the following SQL:

SELECT * FROM events WHERE city = 'Miami' and max_attendees BETWEEN 1 AND 3;

Chapters 3, 4, and 5 of Easy Laravel 5 are devoted to Laravel's powerful database interaction capabilities. In these chapters you'll find plenty of examples demonstrating how to use the where method and much more.