builder

Eloquent Global Scopes make it easy to customize your Model’s queries, however sometimes it is just not enough.

You may want to use similar solution for you DB::table(..) calls as well. While there’s no built-in feature for this, you can still do it with just a little more effort, and here’s how it’s done.

Imagine multi-tenant app where you want to add tenant context to each query (and let it be row-based context, ie. each table has tenant_id column that defines that context):

 

Unfortunately there is no way to inject custom Builder class to the Connection object, because it’s simply instantiated here:

 

It is also not extendable like Eloquent\Builder (MacroableTrait).

 

That said, we need to use custom Connection class that will call our Builder in overriden table method:

 

Next we can adjust the Builder as we need:

This is the minimum, that we need to override for READ operations. Of course there is much more, like handling joins, disabling scope and so on and so forth. Full code will be available on github soon, so stay tuned!

Anyway, there is still one thing missing here – the most important one: IoC binding. In order to use our custom solution, we need to bind the connection in the Container. This will be done in the service provider:

 

Complete solution will let you do for example this (no need for Eloquent Global Scopes on your model anymore):

 

It's only fair to share...Tweet about this on TwitterShare on RedditPin on PinterestShare on FacebookShare on Google+

Related Post

20 Eloquent tricks – more Recently I stumbled upon interesting article by Povilas Korop on laravel-news 20 eloquent tips and tricks. First of all thanks for sharing your knowle...
A story about Laravel Resources Leo is a brilliant developer. He turns every idea into code in no time. He's prepared for any task thrown at him and dives into coding straight away, ...
How to add custom casters in Laravel tinker I made a series about psysh and Laravel's tinker - powerful REPL where you can play with your whole application. ICYMI check it out here: tinker li...
Too much M4g1c will kill you (or at least bite you... So, as you know, I'm a big fan of Laravel, in particular Eloquent is my favourite. The beauty and value of both is a lot of conventions and magic...