Like local scopes for repeating eloquent conditions we can use global scope also to all queries of a given model. However, unlike local scope we do not have to mention its name in controller in model queries. It is applied automatically.
For example, if local scope looks like below in model
//In Post.php public function scopeUserIdOfList( $query ) { return $query->where( 'user_id', 4 ); }
Then, global scope looks like below in model
//In Post.php
protected static function booted() { static::addGlobalScope('userIdOfList', function (Builder $builder) { $builder->where( 'user_id', 2 ); }); }
Now in Controller if using local scope like below
$julPosts = Post::select([ 'id', 'user_id' ,'title', 'created_at','updated_at'])->userIdOfList()->whereMonth(07)->get(); $augPosts = Post::select([ 'id', 'user_id' ,'title', 'created_at','updated_at'])->userIdOfList()->whereMonth(08)->get();
Then, for global scope it will look like below
$julPosts = Post::select([ 'id', 'user_id' ,'title', 'created_at','updated_at'])->whereMonth('created_at', '07')->get(); $augPosts = Post::select([ 'id', 'user_id' , 'title', 'created_at','updated_at'])->whereMonth('created_at', '08')->get();
So, from above you can notice that we do not need to mention scope name like we did for local scope ( userIdOfList() ).
That is big advantage for global scope which can be also disadvantage.
You may forget the fact of used global scope for queries possibly in two three months and may be surprised to see some unexpected result. So double check Model if there are any of those surprises.
Another disadvantage is global scopes are applied automatically and there are no way to pass parameters to them directly unlike local scopes where you can pass parameters. However, you can use session values in global scope.
Therefore picking right type of scope is important for eloquent queries.