0

I am working on building a front-end for managing users / roles / permissions with the Spatie > Permissions package in the backend.

A feature I am seeking to implement is selecting a Permission and having this selection then display all Users having the selected permission.

Using php artisan tinker, I can use the statement: Spatie\Permission\Model\Permission::with("roles.users")->find(59);, with 59 representing the permission->id in question, and the appropriate results are returned.

My problem is that when I take this code to php and I seek to dd((Permission::with('roles.users')->find(59)); I receive a Error Class name must be a valid object or a string error.

Removing the nested relationship using dd((Permission::with('roles')->find(59)); is treated appropriately by Laravel. However I want access to the Users that have the specified permission.

In short, the nested eager loading seems to be failing, dependent entirely on whether the code is in Laravel or Tinker.

I am using php v7.3.25 and Laravel 8.22.1

Thanks for any help.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
scott_p
  • 57
  • 11
  • try to `Permission::with('roles.users')->find(59)->dd()` anyway, you have extra opening bracket in your code. so, `dd(Permission::with('roles.users')->find(59));` should work – Roman Meyer Mar 07 '21 at 22:32
  • Thanks for the shot. This results in the same error: "Error Class name must be a valid object or a string". I agree that it should work... not sure if it's something with Spatie, Php or the newer Laravel. Dropping the relationship to ```with('roles')``` works - just not chained. And it still works in Tinker, just not from code. – scott_p Mar 08 '21 at 03:01
  • it could be an error somewhere in your relationship method, please provide them too. – Anurat Chapanond Mar 08 '21 at 04:55

1 Answers1

0

Ok. Problem solved. Thanks for those that tried to help - your insistence that it should "just work" led me deeper into the code.

The Spatie Permissions package is well done and well researched. Since I was using it out of the box without further modifications, I assumed that the relationships had been setup correctly, and they were.

The problem is with the default Auth utilized. Spatie wants to use Auth::web whereas Laravel wants to use Auth::sanctum.

Connecting to the User relationship via "roles" was finding a mismatch in the Auth function I had in place and was throwing a generic error. So if anyone else finds this as a problem, ensure you have continuity in your Auth checks and you'll be good to go. Note that this doesn't pose a problem for Tinker, which was why the initial behavior was so perplexing.

scott_p
  • 57
  • 11