laravel-permission: Error "Class name must be a valid object or a string" caused by auth:sanctum middleware
After installing Laravel Sanctum and using the ‘auth:sanctum’ middleware instead of the ‘auth:api’ middleware, see Laravel docs, I cannot eager load users on the Role model. It returns “Class name must be a valid object or a string”.
Before (working, without Sanctum installed) Middleware check in Controllers constructor. The index function returns all roles with eager loaded users and permissions.
class Controller
{
public function __construct()
{
$this->middleware('auth:api');
}
public function index()
{
// Get all roles as array with eager loaded users and permissions
$roles = Role::with('users', 'permissions')->get()->toArray();
// Return response
return response()->json($roles, 200);
}
}
Now (using Laravel Sanctum, throws error) Same middleware check in constructor, but instead of ‘auth:api’, it checks for ‘auth:sanctum’, as per the Laravel docs. The index function should return the same response as before, however it throws “Class name must be a valid object or a string”.
class Controller
{
public function __construct()
{
$this->middleware('auth:sanctum');
}
public function index()
{
// Get all roles as array with eager loaded users and permissions
$roles = Role::with('users', 'permissions')->get()->toArray();
// Return response
return response()->json($roles, 200);
}
}
If I remove the ‘users’ eager load, it does eager load the permissions and return a response. I reckon it has to do with the ‘sanctum’ guard. I tried to initialize the Role model with the ‘guard_name’ attribute, but it returns the same error:
// Get all roles
$role = new Role(['guard_name' => 'web']); // 'guard_name' => 'sanctum' doesn't work either
$roles = $role->with('users', 'permissions')->get()->toArray();
Any ideas on how to eager load the users using Sanctum?
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 15 (4 by maintainers)
It seems that Laravel Sanctums SanctumServiceProvider by default registers the
sanctumguard with'provider' => null:This causes Laravel-Permissions
getModelForGuard()helper function to return nothing when middleware requires thesanctumguard to be authenticated, hence the eager load fails. After manually inserting the guard inauth/config.php, the users could be eager loaded again. Not sure if it’s the best solution though:@JanickOtten thanks, it solves mine too.
Alright
‘defaults’ => [ ‘guard’ => ‘sanctum’, ‘passwords’ => ‘users’, ],
Remigrated everything
Cleared cache
new Error raised :
Method Illuminate\Auth\RequestGuard::login does not exist.
@parallels999 What should i do then ?!