Laravel How to use Scopes for Eloquent Builder

Hello Artisans, today I'll talk about scopes. How we can use scopes to write a better and reusable eloquent query. The scope is one of the best approaches for reusing the same query again and again. So, let's see how we can use it in our application to write easy, maintainable, and reusable code.

Note: Tested on Laravel 9.19

Example

Suppose, we have a system where we need to see the active users in various places. Typically, what we do that is we write a query like below

$active_users = User::where('status', 1)->get();

which will be lengthier and not so much efficient. But the same query if we write with scope then it'll look like below.

$active_users = User::active()->get();

where we've to add this scope called active in our User.php model class like below

app/Models/User.php
class User extends Model
{
    public function scopeActive($query)
    {
        return $query->where('status', 1);
    }
}

Now if we use active() method it'll return the active users only. No need to write manually where() condition everywhere.

That's it for today. I hope you've enjoyed this tutorial. Thanks for reading.