Laravel query scopes: cleaner, reusable Eloquent queries

Laravel query scopes: cleaner, reusable Eloquent queries
Laravel scopes come in very handy when you need to run the same query more than once. They also make your queries easier to read and to maintain.

If you are not yet familiar with Laravel scopes, this is the tutorial for you 😉.

What scopes are

Laravel has two kinds of scope, global and local. To keep things simple I will only cover local scopes here, but do take a look at global scopes when you get the chance.

So what is a local query scope in Laravel? Glad you asked. Here is an example of a local scope inside a user model:

php
<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class User extends Model
{
    public function scopeAdmin($query)
    {
        return $query->where('admin', 1);
    }
}

In the code above, the scopeAdmin method returns a $query where the admin column is set to 1. Now that you have seen a local scope, let us look at how to use it.

How to use scopes

To use our scopeAdmin inside the project and get a collection of our admin users, all we have to write is this:

php
$admins = User::admin()->all();

That gives us every admin in the database.

Hopefully you can already see how powerful they are, how much time scopes save and how much more readable they make your code. If you are still not sold on scopes, read on for an example of how they make life easier.

Why use scopes

Taking the previous examples, say we want to change the query so that it only returns the admin rows where the active column is set to 1. Without scopes in the application, we would have to hunt down every occurrence of this query in the codebase:

php
$admins = User::where('admin', 1)->all();

And replace them with:

php
$admins = User::where('admin', 1)->where('active', 1)->all();

With scopes, on the other hand, we simply change the scope itself:

php
public function scopeAdmin($query)
{
    return $query->where('admin', 1)->where('active', 1);
}

Every existing query then returns the admin users where active is 1. As you can see, your code becomes more efficient, easier to maintain and easier to read.

Conclusion

Using scopes in a Laravel application puts the logic in your Eloquent models instead of scattering it through your views and controllers. That makes the project easier to maintain and easier to read.

I hope this article has given you a better grasp of Laravel scopes, and that you will reach for them in your next Laravel projects ✌️.

Laravel

Damien Flandrin Web developer since 2010, creator of Gekkode and Email Impact. Every article is tested on a real project before publication. Contact
Newsletter

New tests, tutorials and projects, by e-mail.

Reproducible tests, versioned code, dated results. Never any spam.