Translate: Laravel: Get Sanctum token by user ID
P粉982054449
P粉982054449 2023-07-30 15:35:48
0
1
585
<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>
P粉982054449
P粉982054449

reply all(1)
P粉638343995

To get the token, you need to add the ->get() function.

The correct code is:


$tokens = $user->tokens()->get();

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:


$user->tokens()->orderBy('created_at', 'DESC')->first();

Please note that the tokens are stored in the personal_access_tokens table and the foreign key is tokenable_id.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template