When I've tried to make things like this automatic, I've always regretted it later. Either it was not obvious and it caused me to debug things longer or I had to change the logic because business rules changed. I would suggest that you keep it at the perimeter of your app and very explicit.
Jul 2, 2021
2
Level 2
Add Global Scope but only for API routes
I have a global scope that attaches to a model and adds an additional where clause to my database queries; however, it gets this information to add to the where clause from from the session variables.
I would like to take advantage of this global scope on my API calls, but obviously do not have access to session variables. Is there a way to detect that the API route is calling and do some modification to the global scope to make this work for the API routes? Below is my global scope its for Tenant... learned this from one of the Laracasts multi-tenant videos
class TenantScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
if(session()->has('tenant_id'))
{
$builder->where('tenant_id', '=', session()->get('tenant_id'));
}
}
}
Please or to participate in this conversation.