Adding multiple filters to the query dynamically in Laravel

|
| By Webner

Laravel: Adding multiple filters to the query dynamically

There may be some situations when the user has the facility to apply some filters on a set of objects. For Example – when we visit the e-commerce sites, there are certain filters like price range, brand, sort by – price low to high, etc.

On applying any or all the filters we check in the backend code that if a particular set of filters is applied then we write one query for that and if a different set of filters is applied we write a different query and so on.

In order to overcome this rewrite of a query with specific filters, we can use Laravel Model and built a query based on filters also.

Example –

Let us take a situation where we want to apply a filter on a set of vehicles and display filtered vehicles result on the webpage. There can be various filters on the page from which the user can apply any no of filters to get the result.

For this purpose, we can apply query like this —

$vehicles = new Vehicles();
$vehicles = $vehicles->select('name','price','year','color');
if (isset($request->name)) {
$vehicles = $vehicles->where('name like (?)',["%$request->name%"]);
}
if (isset($request->year)) {
	$vehicles = $vehicles->where('year',$request->year);
}
$vehicles = $vehicles->get();

Here, We are creating a new object ‘$vehicles’ of the ‘Vehicles’ object. Then we are specifying the columns to get in the resultant object through ‘select()’ function of laravel query builder.

Through “if (isset($request->name))” , we are checking if the particular filter is applied by the user or not. If yes then we are adding the condition to the query in the object we have created through the where() function of laravel query builder.

It will apply all the filters to the query one by one based on the user input and we can get the result at last through get() function.

Leave a Reply

Your email address will not be published. Required fields are marked *