search

Home  >  Q&A  >  body text

Translate: Laravel: Get Sanctum token by user ID

<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粉982054449P粉982054449486 days ago567

reply all(1)I'll reply

  • P粉638343995

    P粉6383439952023-07-31 09:03:30

    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.

    reply
    0
  • Cancelreply