Laravel — Global Scopes for Force Restricting Data

Restricting access/modification of data for a user is one of the most important parts of application development. In most cases, we have to make sure that our application user is limited to its own data created space. Writing Authorization checks and filters in various parts of our code is one way to do it. Or, use the Global Filters Scope feature of Laravel. With this feature you can be sure that no matter from which part of your application tries to access a model (using Eloquent query methods like find, all, where and so on), it will always filter out the data that is owned only by that User.

Example :-

A User always needs to be restricted to accessing/updating his own Order.

Following code can be added to the Order Model

/**

* The “booted” method of the model.

*

* @return void

*/

protected static function booted()

{

static::addGlobalScope(‘forceFilter’, function (Builder $builder) {

$builder->where(‘user_id’, Auth::user()->id);

});

}

This is an Anonymous type of Global Scope (Closures) used. You can also implement it using a separate class.

Note: In the above example, you will probably have an Admin/Seller role too, in such cases, use role based conditions to determine if to apply or not apply the where clause.

You can also exclude this filter when writing queries outside the Model, using the withoutGlobalScope method.

Laravel Documentation Link for Global Scopes : https://laravel.com/docs/8.x/eloquent#global-scopes

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store