Skip to content
Advertisement

Laravel Eager Loading – Unexpected Behavior Difference between Code and Tiner

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: SpatiePermissionModelPermission::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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement