I'm trying to get the user's Sanctum token based on the user ID, but I'm not able to succeed. The application is a single page application using React Native as the frontend and Laravel as the backend.
I tried the following method but got an empty object.
$user = User::find($request['user_id']); $tokens = $user->tokens();
This is how I create the token when the user registers:
$user = new User(); $user->name = 'Name'; $user->save(); $token = $user->createToken($request->input('device_name'))->plainTextToken; $user = $user->fresh();
Was the token created correctly? After using createToken, do I need to save it again?
To get the token, you need to add the ->get() function.
The correct code is:
This is because $user->tokens() returns a query builder object, so you can append all the query builder functions to filter, sort and select tokens.
For example:
Please note that the tokens are stored in the personal_access_tokens table and the foreign key is tokenable_id.