laratrust icon indicating copy to clipboard operation
laratrust copied to clipboard

Wrong role loaded inside Model's relationship

Open DePalmo opened this issue 1 year ago • 0 comments

  • Laravel Version: 10.26.2
  • Laratrust Version: 9.2.1

Describe the bug I'm having a problem checking for user's permission that was assigned through a role. The check is being done in another HasManyThrough relationship I created. Imagine a system with multiple roles that have various permissions assigned per role and each user has only one role assigned to. I want to load user's role and check for a specific permission in order to load with trashed records or without.

To Reproduce This is in my model (have added comments for dd() what works and what doesn't):

 public function reports()
    {
        $query = $this->hasManyThrough(
            Report::class,
            ReportSuspect::class,
            'company_id',
            'id',
        )->withAnonymized();

        dd([
            User::with('roles')->find(\Auth::id())->roles->first()->toArray(), - works, but I don't like this approach
            request()->user()->roles->first()->toArray(), - loads first role in the system, not first assigned to the user
            request()->user()->roles()->first()->toArray(), - same as above
            Auth::user()->roles->first()->toArray(), - same as above
            Auth::user()->roles()->first()->toArray(), - same as above
            Auth::user()->hasPermission('can-see-deleted-reports') - returns true, despite the user's role does NOT contain this permission,
        ]);

        // I expected that I can check for permission like this. Surprisingly this code works in a Controller or Resource,
        // but not in a Model where I create a relationship.
        if (request()->user()->hasPermission('can-see-deleted-reports') || request()->user()->role === 'super-admin') {
            $query->withTrashed();
        }

        return $query;
    }

EDIT: I also want to add that when doing a dd(request()->user()) and checking the response, I see that roles relationship does NOT contain only the role assigned to the user, but a large collection of 282 roles. In the system I have total of 26 roles.

DePalmo avatar Sep 16 '24 06:09 DePalmo