I keep getting this error: Field 'api_token' doesn't have a default value in PHP Laravel 5.5

I keep getting this error: Field 'api_token' doesn't have a default value in PHP Laravel 5.5

我是 laravel 的新手。我正在尝试制作 api。因此,如果您注册为 (auth) 用户,您将获得一个 api_token 以便您可以访问仪表板 这是我的一些代码。当我尝试注册时,它给了我这个错误:

照亮\数据库\QueryException (HY000) SQLSTATE[HY000]: 一般错误: 1364 字段 'api_token' 没有默认值 (SQL: 插入 users (name, email, password, updated_at, created_at) 值 (goddies, f@gmail.com, $2y$10$uKJPI9hBJSdygMf7MefP1eM1GQ7VM3s74eVy5qcuFj4/s8HH2Iun., 2017-11-13 19:11:38, 2017-11-13 19:11:38))

关于我为用户迁移:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('api_token', 20)->unique();
        $table->rememberToken();
        $table->timestamps();
    });
}


public function down()
{
    Schema::dropIfExists('users');
}

}

这是我的用户模型:

<?php

namespace App;

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

class User extends Authenticatable
{
    use Notifiable;

protected $fillable = [
    'name', 'email', 'password', 'api_token',
];

protected $hidden = [
    'password', 'remember_token', 'api_token',
];

}

该错误表明在创建新记录时 api_token 字段为空。这就是错误显示 "it doesn't have a default value".

的原因

修改 UserController 中的 store 方法(或用于保存新记录的方法)并为 api_token 字段生成一个值:

public function store(Request $request)
{
    // some validation logic
    $user = new User;
    $user->name = $request->name;
    $user->email = $request->email;
    $user->password = $request->password;
    // ... the rest of your fields

    // to generate a new token for the new user
    $user->api_token = str_random(20);

    // then save
    $user->save();

    return $user;
}

观测:

如果您使用 factory/seeder,您将需要生成该字段或使数据库中的该列可为空。

如果您想避免此错误,您需要将列 'api_token' 设置为可为空,以便在您的请求 [=15] 没有值时它具有默认值 'NULL' =],

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('api_token', 20)->unique()->nulllable();
        $table->rememberToken();
        $table->timestamps();
    });
}


public function down()
{
    Schema::dropIfExists('users');
}

希望这对您有所帮助 :)

该错误表明 api_token 字段为空或在创建新记录时未设置为 NULL。这就是错误显示它没有默认值

的原因

因此您可以简单地修改用户 table 的列并将 default 值设置为 NULL 并插入新记录。