Home

1 minute read

Laravel Scopes

Tony Lea

Laravel Scopes

Laravel scopes can come in really handy when you need to query data multiple times. It will also make your queries easier to read and manage.

If you are unfamiliar with Laravel Scopes. This is the tutorial for you 😉.

What are scopes

There are two types of scopes in Laravel (Global and Local). In order to keep this simple, I am only going to cover local scopes; however, you should check out 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 of an example User Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

In the code example above, you can see that we have the scopeAdmin method, which returns a $query where the column admin is set to 1. Now, that you've seen an example of a local scope, let's learn how to use it.

How to use scopes

If you want to use our scopeAdmin inside of our project to get a collection of our admin users, we could simply write the following code:

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

This will now give us all the admin users in our database.

Hopefully, you can see how powerful these can be and how scopes can save you time and make your code more readable. If you still aren't sold on scopes, continue reading for an example of how they can make your life easier.

Why use scopes

Taking our previous code examples, let's say that we wanted to change our query to return only the admin users where the column active is set to 1. If we were not using scopes inside of our application, we would have to search our codebase for the following query:

Checkout our latest product - the ultimate tailwindcss page creator 🚀
$admins = User::where('admin', 1)->all();

And replace them with:

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

However, if we were using scopes we could simply change our scope to the following:

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

And all of our current queries will get our admin users where active is set to 1. As you can see this will make your code more efficient, maintainable, and easier to read.

Conclusion

Using scopes in your Laravel application will add logic to your Eloquent Models instead of directly in your Views and Controllers. This will make your project easier to maintain and read.

I hope this article has helped you understand more about Laravel Scopes and I hope that you will use them in your future Laravel projects ✌️.