How To Use Scope In Laravel

Laravel gives you access to many useful methods that you can use to narrow the results of your Eloquent queries.

Occasionally you need to use the same conditions more than once. In that scenario, you can use scope. Let's look at how to add scopes to Laravel models easily.

Scopes is a feature of Laravel that lets you wrap your conditions into a reusable, simple statement. We'll demonstrate how easily you can add scopes to your Laravel models.

Using Scope in Laravel

Imagine that you are making a to-do list application and that you need to get all completed tasks in different places. To retrieve all the tasks that have already been completed, you can use the following condition:


$completedTodos = Todo::where('completed', 1)->get();


You may use the above condition more than once in your application. Laravel scopes can be used to make the code clean. The scope is just a method in your model that you can use to wrap up the syntax needed to run a query like the one above. Scopes are set by putting "scope " in front of the name of a method, as shown below.


class Todo extends Model
{
    public function scopeCompleted($query)
    {
        return $query->where('completed', 1);
    }

}


With the scope mentioned above, you can do it this way:


$completedTodos = Todo::completed()->get();

Laravel Dynamic Scope

On the other hand, if you want this scope to be dynamic and you want to get completed or not-completed to-dos, then you may pass an argument. Construct a parameter as you would for any other model method. This will allow you to get the to-dos based on your passing parameter to the method.


class Todo extends Model {

    public function scopeCompleted($query, $arg)
    {
        return $query->where('completed', $arg);
    }
}


After you have specified the parameter, you may apply the scope in the following way:


// Get completed todos
$completedTodos = Todo::completed(1)->get();

// Get incomplete todos
$nonCompletedTodos = Todo::completed(0)->get();


Laravel Scope with Relation

You'll usually want to use scopes with relations. For example, you can get a list of a user's to-do items like the below:


$user = User::findOrFail(1); // 1 is user id
$completedTodos = $user->todos()->completed(1)->get();


When working with Laravel scopes, it is advisable to do so when you have several repeated queries and want to reuse the code.