Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

andersb's avatar

Creating an API Token when a user signs up

I am trying to automatically create an API Token when a user signs up using Laravel Spark, but I keep getting an error Call to undefined method App\Listeners\CreateApiToken::createToken()

Here is the approach I found relevant:

Firstly I added an event CreateApiToken which is registred in app/Providers/EventServiceProvider.php as:

'Laravel\Spark\Events\Auth\UserRegistered' => [
    'App\Listeners\CreateApiToken',
],

Secondly I created a listener app/Listeners/CreateApiToken.php as:

<?php

namespace App\Listeners;

use Laravel\Spark\Events\Auth\UserRegistered;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Laravel\Spark\Contracts\Repositories\TokenRepository;
use Laravel\Spark\User;

class CreateApiToken
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  UserRegistered  $event
     * @return void
     */
    public function handle(UserRegistered $event)
    {
        $event->user->createToken('default')->token;
    }

Does anyone know, why the createToken() method cannot be used?

0 likes
4 replies
Cronix's avatar

I can't find a createToken method in spark for the user (or tried to do this). Here's where I see they create an API token for a user, so maybe that will help:

public function store(CreateTokenRequest $request)
{
    $data = count(Spark::tokensCan()) > 0 ? ['abilities' => $request->abilities] : [];

    return response()->json(['token' => $this->tokens->createToken(
        $request->user(), $request->name, $data
    )->token]);
}

/vendor/laravel/spark/src/Http/Controllers/Settings/API/TokenController.php

andersb's avatar

Dear @Cronix, I found the same code, but I have so far been unable to get me head around using this.

Spark uses the following API route for creating an API token from backend:

$router->post('/settings/api/token', 'Settings\API\TokenController@store');

which uses a token repository instance to save the token. But I don't understand what I need to implement to get the ability to create tokens for a given user.

beetuco's avatar
beetuco
Best Answer
Level 9

@andersb I had a need to create a sort of default api token for each user and this is how I've done it... Would like some other peoples opinion about a better way to do this.

In your listener class:

use Laravel\Spark\Repositories\TokenRepository;
use Laravel\Spark\Spark;
use Laravel\Spark\Events\Auth\UserRegistered;

Inject the TokenRepository

private $tokenRepository;

    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct(TokenRepository $tokenRepository)
    {
        //
        $this->tokenRepository = $tokenRepository;
    }

Then create that token...

public function handle(UserRegistered $event)
    {
        $this->tokenRepository->createToken($event->user, 'default-mobile-token', [
            'abilities' => [
                'read-servers',
                'create-servers',
                'delete-servers',
            ]
        ]);
    }

Also, this solution is very tightly coupled to registering a user.. what if they user deletes the key via settings, or we need to re-create it, or the team is switched or need to implement a guard on it. I think this action under handle should really be delegated to a class that can itself implement the token repository and handle a full suite of checks and balances.

1 like
andersb's avatar

@beetuco this looks like a really good approach. I ended up doing it much more manually right now. I will try with your solution.

1 like

Please or to participate in this conversation.