Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wrong role loaded inside Model's relationship #682

Open
DePalmo opened this issue Sep 16, 2024 · 0 comments
Open

Wrong role loaded inside Model's relationship #682

DePalmo opened this issue Sep 16, 2024 · 0 comments

Comments

@DePalmo
Copy link

DePalmo commented Sep 16, 2024

  • 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant