Search code examples
laraveltokenlaravel-sanctum

L8 - Sanctum - Add my own token with migration


I’m using Laravel 8 with Sanctum.

Is there a way to create a migration, or what is the best practice, to add some default token every time I redeploy my project?

Thank you.


Solution

  • You can use User factory for this:

    public function configure()
    {
        return $this->afterCreating(function (User $user) {
            //You need to use some condition in user to determine, make token or not 
            if($user->isAdmin){
                $user->tokens()->create([
                    'name' => 'default_token',
                    'token' => 'default_token_value',
                    'abilities' => '*',
                ]);
            }
        });
    }
    

    If user is admin - after creating - factory make default token for them.

    Than, you can use factory in your seeder/tests/etc.