Laravel Scope With Example Usage

  • 02-12-2022
  • 482
  • Laravel 9
  • Haresh Chauhan

What is scope of Laravel?

Laravel scope is just a simple method that you can define in your model and use repetitively in various controllers with the same logic which you applied in scope using the defined model in the controller. For defining the scope method in your model system is prefix "scope" also should be written before any method name.

Example 1

I am taking for a user model example, here in the user model I am defining two scopes for the active user and inactive user. So if I want to task the user list only active users I will call active scope else for inactive I will call inactive scope.

class User extends Authenticatable
{
    public function scopeActive($query)
    {
        $query->where('status',1);
    }

    public function scopeInactive($query)
    {
        $query->where('status',0);
    }
}

Above define the user model scope user in practically.

$usrs = User::active()->toBase()->get();

Example 2

I have defined scope as filtering a user who is an admin in all among the users in the user's table. Therefore I define an admin scope using this scope I will get only admin users.

class User extends Authenticatable
{
    public function scopeAdmin($query)
    {
        $query->where('is_admin',1);
    }
}

If users apply admin filter the when the method will accept the true boolean and return admin users from the user's table.

User::when($request->has('admin'),function($query){
    $query->admin();
});

Example 3

In this example, I defined a category id filter scope in the category model, also the only thing I passed was a category id argument in this scope method.

class Category extends Model
{
    public function scopeCategory($query,$categoryId)
    {
        $query->where('category_id',$categoryId);
    }
}

If the when() method accepts the request method with the category id then it will find scope from the model and filter with the category matching id.

User::when($request->has('category_id'),function($query){
    $query->category(request('category_id'));
});

We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :