How to use Query Scopes or Scope Filters in Laravel

laravel scope filters

Hi guys 🙂 in today’s tutorial, we will be looking at scope filters in Laravel. Laravel offers scope filters in which we can filter parameters from a model in the app. This applies best when you are implementing search requests within your app.

So how do we go about it?. Let’s explore…

Step 1

Start with the model. This means that you need to have a search form in which you want to make search requests in your database.

So am going to use my application to explain how to implement the scope filters in laravel. Update the model with this code. For example, mine is a blog website made purely in laravel.

Post.php

  public function scopeFilter($query, array $filters) {
        if($filters['search'] ?? false) {
            $query->where('title', 'like', '%' . request('search') . '%')
                ->orWhere('slug', 'like', '%' . request('search') . '%')
                ->orWhere('details', 'like', '%' . request('search') . '%');
        }
    }

Now with this code, we are defining the scope filter function which contains the if statement. The where clause checks different parameters in which the filtering is done.

You can filter different parameters from your model. Let’s say it’s an eCommerce website where you have different parameters like product, colour, brand, price etc.

Step 2

Once this is done you will need to update the controller that’s associated with the model. In my case, this is the one.

PagesController.php

class PagesController extends Controller
{
    public function index()
    {
        $posts = Post::inRandomOrder()->where('post_type', 'post')->where('is_published', '1')->filter(request(['search']))->paginate(3);
        return view('pages.index', compact('posts'));      
    }

Take note of where I have placed the

filter(request(['search']))

that’s where you will update your function with.

Step 3

The next thing is to have a search form like this… this code is from my nav.blade.php

Nav.blade.php

<form action = "/" method="get" class="form-inline">
              {{csrf_field()}}
              <div class="input-group search-box">
                <input type="text" name="search"  class="form-control" placeholder="Type a Query..." aria-label="Search for..."  id="q">
                <span class="input-group-btn">
                  <button class="btn btn-secondary" type="button"><i class="ion-search"></i></button>
                </span>
              </div>
            </form>

From the above search form, action is set to"/"which means when someone types a query he/she will be redirected back to the home page with the relevant result. We are done!

You can implement the same on other models, for example, if you have an admin side with a search form you can apply the same concept.

Sign up for free tutorials in your inbox.

We don’t spam! Read our privacy policy for more info.

Leave a Comment

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