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 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 Chauhan
(Co-Founder)We Are Also Recommending You :
- Median() Method | How It is Different From avg() Method In Laravel Collection
- Email Send Using Queue In Laravel
- HTTP Client Guzzle Package With Basic Usage In Laravel
- Firebase Dynamic Links Shorten URL PHP Function
- [issue] Possible All Way To Change Asset Path And Add Public To Asset Path In Laravel
- Laravel 6 Create Custom Helper Function
- How To Use Where Clause With Two Fields Of The Same Table Examples
- All Guides About Soft Delete Laravel 8 And 9 With Examples
- Laravel 6 REST API with Passport Tutorial
- How to send mail example in Laravel 6