I found this wonderful resource https://learn2torials.com/a/laravel8-global-model-scope that takes us on a journey to know Scope. Exit fullscreen mode you should override the model's booted method and invoke the model's addGlobalScope method.

In that case you can remove your applied scope using following example # fetch all users weather they are active or not $users = User::withoutGlobalScope(new HasActiveScope)->all(); # fetch active users weather they are deleted or not User::withoutGlobalScope('delete')->all(); Local Scope

In this case instead of defining global scope you can add local scope in your Laravel model like following where('active', 1); } public function scopeDelete($query) { return $query->where('delete', 0); }} use local scope # apply active local scope to following query $users = User::active()->orderBy('created_at')->get(); # apply delete local scope to following query $users = User::delete()->orderBy('created_at')->get(); Dynamic Scopes

In that case we can pass dynamic parameter to our local scope and it will act as dynamic scope where('active', 1); } public function scopeDelete($query) { return $query->where('delete', 0); } public function scopeWithRole($query, $role) { return $query->where('role', $role); }} use dynamic scopes # find active users with role admin $users = User::active()->withRole('admin')->all(); I hope you enjoyed the article and I hope you always enjoy the code.
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners