Laravel / PHP PHP Free

Laravel: Reusable Eloquent Search Scope

Add one search scope to any Eloquent model and search across several columns with a single method call.

22 lines · Updated Nov 26, 2026

Preview of Laravel: Reusable Eloquent Search Scope
laravel-search-scope-eloquent.php
<?php

// In your model, e.g. app/Models/Post.php
public function scopeSearch($query, ?string $term)
{
    if (blank($term)) {
        return $query;
    }

    return $query->where(function ($q) use ($term) {
        $q->where('title', 'like', "%{$term}%")
          ->orWhere('body', 'like', "%{$term}%")
          ->orWhereHas('user', function ($u) use ($term) {
              $u->where('name', 'like', "%{$term}%");
          });
    });
}

// Usage in a controller:
// $posts = Post::search($request->input('q'))
//     ->latest()
//     ->paginate(15);

About this snippet

Almost every admin panel needs a search box, and copying the same where ... like chain into every controller quickly gets messy. This snippet wraps search in a reusable Eloquent local scope: write the logic once in your model, then call Product::search($term)->paginate() anywhere.

How it works

  1. A local scope is a model method starting with scope that receives the query builder.
  2. If the search term is empty, the query is returned unchanged.
  3. Otherwise it adds grouped LIKE conditions across the columns you choose. Grouping them in a closure keeps them from breaking other where conditions such as status = published.

How to use it

  • Add the scope to your model and list the searchable columns.
  • Call it from a controller or Livewire component, chained with filters, ordering and pagination.
  • Values are passed as bindings, so user input is safe from SQL injection.

Performance tips

  • A LIKE '%term%' search cannot use a normal index, so it slows down on very large tables.
  • For prefix searches (term%) add an index on the column.
  • For big catalogues, use MySQL full-text indexes or Laravel Scout with Meilisearch or Typesense.

Common problems

  • Search returns unpublished rows: the OR conditions were not grouped — wrap them in a closure.
  • Searching relationships: use orWhereHas('category', ...) inside the same group.

FAQ

Is it case-insensitive? With MySQL's default collations, yes. On PostgreSQL use ILIKE.

Related: Build a live search with Livewire · Log slow queries

How to install

Add the scopeSearch method to your model and change the column names to match your table. Call it from the controller with the search term from the request.

Share this snippet

See all
Chat with us