Laravel search query with multiple conditions

Laravel search query with multiple conditions

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Handling Multiple Optional Criteria in Laravel Search Queries

Building a search interface that accepts multiple optional parameters requires shifting from simple conditional logic to a more dynamic query construction approach. In the scenario you presented, the DogsController currently uses an if/elseif/else chain to handle searches by name, breed, or default listing. While this works for single-criteria filters, it breaks down when you need to combine conditions like breed, sex, and radius simultaneously. The current structure forces a choice: either search by breed OR return all dogs. It does not support the intersection of these filters.

To handle inputs like search-breed, sex, and miles concurrently, you must construct the query dynamically based on which parameters are present in the request. Laravel's Eloquent ORM provides several tools for this, but the most robust approach involves checking for the existence of input values before adding them to the query builder chain.

First, ensure your database schema supports the necessary joins and columns. You likely have a dogs table and a related breeds table. The radius search adds complexity because it requires calculating distances, typically involving latitude and longitude columns in the dogs table. A standard SQL WHERE clause cannot handle geometric calculations directly without specific extensions or functions (like PostGIS), so you will need to implement the distance logic using Eloquent's geo-query capabilities or a dedicated package like geo-point.

Here is how to refactor the index method to accept all three criteria while maintaining backward compatibility:

public function index()
{
    // Start with a base query on the Dog model
    $query = Dog::query();

    // 1. Handle Name Search (if 'search' exists)
    if (request('search')) {
        $query->where('name', 'like', '%' . request('search') . '%');
    }

    // 2. Handle Breed Search (if 'search-breed' exists)
    if (request('search-breed')) {
        $query->whereHas('breed', function ($q) {
            $q->where('name', 'like', '%' . request('search-breed') . '%');
        });
    }

    // 3. Handle Sex Filter (if 'sex' exists and is not empty)
    if (request('sex')) {
        $query->where('sex', request('sex'));
    }

    // 4. Handle Radius Filter (if 'miles' exists and is valid)
    if (request('miles') && request('latitude') && request('longitude')) {
        // Note: This assumes a geo-distance package or custom logic is set up.
        // Without specific geo-data, this step often requires additional configuration.
        $radius = request('miles');
        // Example using a hypothetical geo-column setup or raw SQL injection for distance
        // $query->whereRaw("ST_Distance_Sphere(location, ST_MakePoint(? , ?)) <= ?", [
        //     $longitude, $latitude, $radius
        // ]);
    }

    // Apply ordering and pagination regardless of filters
    $dogs = $query->orderBy('name')->paginate(5);

    return View::make('dogs.index')->with(array('dogs' => $dogs));
}

The key change here is using the request() helper (or the deprecated Input facade in older Laravel versions) to check for the existence of specific keys. If a key exists, that condition is appended to the query; if it does not exist, the query remains untouched for that specific criterion. This allows a request with all three parameters to result in a query like:

SELECT * FROM dogs 
WHERE (name LIKE '%poodle%' OR breed.name LIKE '%poodle%') 
  AND sex = 'M' 
  -- AND distance_condition
ORDER BY name;

One significant pitfall with this approach is the "OR" logic introduced by multiple whereHas or where calls if not grouped correctly. In the example above, if you search for a specific breed but leave other fields empty, it should only filter by breed. However, if you combine name and breed searches, you are effectively saying "dogs whose name contains X OR whose breed contains Y". If strict logic is required (e.g., dog must match both criteria), you would need to chain the conditions without orWhere.

Additionally, implementing the radius search requires specific database columns for latitude and longitude. Standard MySQL does not support complex distance calculations out of the box without extensions. You might consider using a package like geo-point which adds methods like whereNear() to handle this logic cleanly:

if (request('miles')) {
    $query->whereNear('location', request('latitude'), request('longitude'), request('miles'));
}

Finally, remember that Eloquent's query builder is eager and safe. Always sanitize or validate user inputs before using them in LIKE clauses to prevent SQL injection, although Laravel's binding mechanism handles most cases automatically if you use the request() helper correctly. By decoupling the filtering logic into discrete conditional blocks, you create a flexible search engine that scales as your requirements grow, handling null values naturally by simply skipping those query segments.

Our network