Tutorials, PHP & MySQL, Laravel Framework

Laravel apply a query constraint with global scopes

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();

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.