新用户注册后,Laravel 5.8无法生成api_token

时间:2019-04-09 19:13:15

标签: laravel api

我正在玩Laravel身份验证。

在带有Composer的新创建的Laravel应用中,我一直按照说明进行操作,直到这一点为止(包括在内)

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

但是,当我注册一个新用户时,api_token字段为NULL。

当用户注册时,我还需要做些什么才能开始生成api令牌?

在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),
    ]);
}

迁移(我称其为Token)以更新用户表:

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);
        });
    }

应用\用户模型:

<?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',
    ];
}

2 个答案:

答案 0 :(得分:1)

在您的用户模型中,将“ api_token”添加到您的填充物中

class User extends Authenticatable
{
    use Notifiable;

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

答案 1 :(得分:1)

创建迁移后,运行the migrate Artisan命令:

php artisan migrate

如果您使用的是Homestead virtual machine,则应在虚拟机中运行以下命令:

php artisan migrate --force