Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.8 cannot generate api_token when new user register

Tags:

laravel

api

I am playing around with Laravel Authentication.

On a freshly created Laravel app with Composer, I followed literally the instructions until this point (included)

https://laravel.com/docs/5.8/api-authentication#generating-tokens

When I register a new user, however, the api_token field is NULL.

What else do I need to do in order to start generating the api token when a user registers??

Create method in RegisterController:

protected function create(array $data)
{
    return User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => Hash::make($data['password']),
        'api_token' => Str::random(60),
    ]);
}

Migration (I called it Token) updating the users table:

class Token extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('api_token', 80)->after('password')
            ->unique()
            ->nullable()
            ->default(null);
        });
    }

App\User model:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}
like image 671
Enrico Avatar asked Apr 09 '19 19:04

Enrico


2 Answers

In your user model add 'api_token' to your fillables

class User extends Authenticatable
{
    use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 
    'email', 
    'password', 
    'api_token'
];
like image 166
FunkyMonk91 Avatar answered Sep 24 '22 08:09

FunkyMonk91


After creating migration , run the migrate Artisan command:

php artisan migrate

If you are using the Homestead virtual machine, you should run this command from within your virtual machine:

php artisan migrate --force
like image 41
Muath Avatar answered Sep 24 '22 08:09

Muath