Search code examples
laravellaravel-airlock

laravel airlock issue with creating tokens: 'tokenable_id' cannot be null


Have upgraded to Laravel 7 and have installed Laravel/Airlock.

Having followed the installation instructions if try to create a token i get an error

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'tokenable_id' cannot be null (SQL: insert into personal_access_tokens (name, token, abilities, tokenable_id, tokenable_type, updated_at, created_at) values (api-token, 31afd4da089878bd2cd562264bd2d8c789c7a1f91e47f6c3969bce2fc19a7329, ["order:create","order:view","WLR3:check_availability"], ?, App\Models\User, 2020-03-06 10:44:05, 2020-03-06 10:44:05))

in my TokenController.php i have:

public function create(User $user, Request $request)
{
    $token_name = $request->input('token_name', 'api-token');

    $abilities = $request->input('abilities', [
        'order:create',
        'order:view',
        'WLR3:check_availability'
    ]);

    $token = $user->createToken($token_name, $abilities);

    return $this->view($user, $request);
}

What have i missed that could be causing this error?

On the User Model it starts with:

use Laravel\Airlock\HasApiTokens;

class User extends Authenticatable /* implements MustVerifyEmail */
{
    use HasRoles, HasApiTokens, Notifiable;

    protected $guard_name = 'web';

Solution

  • Rookie mistake... It seems that the $user created on the dependency injection was not a valid one.

    I need to add:

    $user = Auth::user();
    

    to the create method, so it now reads as:

    public function create(Request $request)
        {
            $user = Auth::user();
    
            $token_name = $request->input('token_name', 'api-token');
    
            $abilities = $request->input('abilities', [
                'order:create',
                'order:view',
                'WLR3:check_availability'
            ]);
    
            $token = $user->createToken($token_name, $abilities);
    
            return $this->view($user, $request);
        }
    

    this now works!