I need to apply specific global scope only if authenticated user's role is equal to something. So that user with certain role will only be able to execute queries on a given subset of records.
I can easily deal with User model (of currently logged in user) but not inside scope's apply method.
https://github.com/laravel/framework/issues/22316#issuecomment-349548374
The scope constructor executes very early, before the auth middleware has run. Resolve the user within the apply method, not in the constructor.
OK, so I'm inside the apply
method:
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class UserScopeForSalesContactAdmin 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)
{
dd('within apply', auth()->user());
dd(auth()->user()); // won't work
$builder->where('foo', '=', 'something from currently logged in user');
}
}
Obviously second dd
gives:
Maximum function nesting level of '512' reached, aborting!
How to resolve this? I imagine I should call IOC container via app()->make()
but then?
Thanks for any hints.
edit: I think I see what's causing the infinite loop (https://github.com/laravel/framework/issues/26113) but still I need to find a best way to obtain the User…