Laravel apply a query constraint with global scopes

David Carr

Laravel Framework PHP & MySQL Tutorials

Imagine your building a multi-tenancy application, in your controller your using a Contacts model every single time you pull a query out it needs constraining to the current tenant like this:

$contacts = Contact::where('tenant_id', session('tenant_id')->paginate();

Using a global scope would mean the constraint could be applied to all your queries automatically.

In your model using the static boot method. Add a static addGlobalScope the first param is the name of the scope and the second is a closure which is type hinted to use $builder. 

Inside the closure add the where constraint. In this case I'm saying where the tenant_id matches a tenant_id stored in a session.

protected static function boot()
{
    parent::boot();

    //apply condition to all queries
    static::addGlobalScope('tenent', function (Builder $builder) {
        $builder->where('tenant_id', session('tenant_id'));
    });
}

Import the builder

//import Builder
use Illuminate\Database\Eloquent\Builder;

Now this will be applied automatically to your queries so pull all contacts is now simplified to this:

$contacts = Contact::paginate();

 

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

Help support the blog so that I can continue creating new content!

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.