Translate: Laravel: Get Sanctum token by user ID
P粉982054449
2023-07-30 15:35:48
<p>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. </p><p>I tried the following method but got an empty object. </p><p><br /></p>
<pre class="brush:php;toolbar:false;">$user = User::find($request['user_id']);
$tokens = $user->tokens();</pre>
<p>This is how I create the token when the user registers: </p>
<pre class="brush:php;toolbar:false;">$user = new User();
$user->name = 'Name';
$user->save();
$token = $user->createToken($request->input('device_name'))->plainTextToken;
$user = $user->fresh();</pre>
<p>Was the token created correctly? After using createToken, do I need to save it again? </p>
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.