Where and If Statements Laravel Eloquent
Stefan Bogdanescu
Founder & Senior Architect · 2026-06-29
Introduction
Laravel is an excellent PHP framework that provides a set of powerful tools for developers. One such tool is its Object Relational Mapping (ORM) called Eloquent, which makes working with databases much easier and faster. You can achieve complex queries using its elegant syntax while maintaining good performance. In this blog post, we'll be focusing on how to apply multiple conditions in your search query using if statements within Laravel Eloquent’s WHERE clause.Filterable Search with Simple Conditions
The following examples show you the basic usage of Laravel's Eloquent for simple filtering queries: 1. Retrieving all records from a table:php
$data = Scrapper::paginate(15);php
$database = new Scrapper;
$database->get();php
$database = new Scrapper;
if (isset($_GET['cat-id'])) {
$database->where('cat_id', '=', $_GET['cat-id']);
}
$database->get();Combining Multiple Filters with IF Statements
Now let's assume you want to implement multiple filters based on user input, such as category ID, price range, and search string: 1. Filtering by specific category ID:php
$database = new Scrapper;
if (isset($_GET['cat-id'])) {
$database->where('cat_id', '=', $_GET['cat-id']);
}php
if (isset($_GET['band'])) {
$high = isset($_GET['band']['high']) ? intval($_GET['band']['high']) : null;
$low = isset($_GET['band']['low']) ? intval($_GET['band']['low']) : null;
if ($high && $low) {
$database->where('price', 'BETWEEN', $high, 'AND', $low);
} else if ($high) {
$database->where('price', '>', $high);
} else if ($low) {
$database->where('price', '<=', $low);
}
}php
if (isset($_GET['search'])) {
$search = $_GET['search'];
$database->where('title', 'LIKE', '%'.$search.'%');
}php
$database = new Scrapper;
if (isset($_GET['cat-id'])) {
$database->where('cat_id', '=', $_GET['cat-id']);
}
if (isset($_GET['band'])) {
$high = isset($_GET['band']['high']) ? intval($_GET['band']['high']) : null;
$low = isset($_GET['band']['low']) ? intval($_GET['band']['low']) : null;
if ($high && $low) {
$database->where('price', 'BETWEEN', $high, 'AND', $low);
} else if ($high) {
$database->where('price', '>', $high);
} else if ($low) {
$database->where('price', '<=', $low);
}
}
if (isset($_GET['search'])) {
$search = $_GET['search'];
$database->where('title', 'LIKE', '%'.$search.'%');
}
$database->get();Conclusion
In conclusion, you can easily implement multiple filters with Laravel Eloquent's WHERE clause and if statements. This approach allows you to have dynamic filterable search functionality on your website based on user input. Remember to optimize your queries for better performance, and use the query builder whenever possible. Happy coding!