Search code examples
laraveloauthlaravel-passport

Laravel Passport - Automatically create token when a user is created


I have been looking into using Passport to allow api access to my Laravel App. I have successfully implemented it using the standard tutorial from the Laravel docs.

I don't want an oauth management screen as described in the tutorial, I just want to be able to register a user using the App and have it automatically create the tokens it needs for that user.

Is this possible and does anybody have an example they can point me at?


Solution

  • $tokenStr will give you the new generated token for that specific user.

    $newUser = User::create();
    $userObj = User::find($newUser->id);
    $tokenStr = $userObj->createToken('Token Name')->accessToken;
    
    // or try this.
    
    $newUser = User::create();
    $tokenStr = $newUser->createToken('Token Name')->accessToken;