Laravel 5 枚举类型在创建时失败

Lau*_*ent 2 php mysql enums models laravel-5

这里真的很奇怪的问题。我正在通过 为我的网站生成管理员,\Console\Command并且在某些时候我显然创建了它。

$user = User::create([

    'first_name' => 'Admin',
    'last_name' => 'Inistrator',
    'phone' => '',

    'email' => $email,
    'password' => bcrypt($password),
    'role' => 'admin',
]);
Run Code Online (Sandbox Code Playgroud)

我的数据库中的结果是该帐户获得了一个user角色而不是admin,但是如果我这样做

$user = User::create([

    'first_name' => 'Admin',
    'last_name' => 'Inistrator',
    'phone' => '',

    'email' => $email,
    'password' => bcrypt($password),
    'role' => 'admin',

    ]);

$user->role = 'admin';
$user->save();
Run Code Online (Sandbox Code Playgroud)

然后它完美地工作。我怀疑 Laravel 5 在我创建一个新帐户时会做一些奇怪的事情,该帐户将与所有特征相关联,等等与User模型相关联......你怎么看?

PS:这是我的迁移表

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

class CreateUsersTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function(Blueprint $table)
        {

            $table->increments('id');

            $table->string('first_name');
            $table->string('last_name');
            $table->string('phone');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->enum('role', ['user', 'business', 'admin']);

            $table->rememberToken();
            $table->timestamps();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {

        Schema::drop('users');

    }

}
Run Code Online (Sandbox Code Playgroud)

Lau*_*ent 5

我发现了问题。由于DB::getQuerylog()(我也可以DB::listen按照答案中的说明使用),我听取了查询

查询是:

    \DB::enableQueryLog();

    $user = User::create([

        'first_name' => 'Admin',
        'last_name' => 'Inistrator',
        'phone' => '',

        'email' => $email,
        'password' => bcrypt($password),
        'role' => 'admin',

        ]);

    dd(\DB::getQueryLog());
Run Code Online (Sandbox Code Playgroud)

结果是:

array:1 [
  0 => array:3 [
    "query" => "insert into `users` (`email`, `password`, `updated_at`, `created_at`) values (?, ?, ?, ?)"
    "bindings" => array:4 [
      0 => "klklm"
      1 => "$2y$10$RUorxAp4EbN/7TvEmdk.dudBBb0dgUWhmAvRsjXgVFubhEKbaLR4K"
      2 => "2015-04-13 10:30:36"
      3 => "2015-04-13 10:30:36"
    ]
    "time" => 3.17
 ]
]
Run Code Online (Sandbox Code Playgroud)

所以我意识到我的领域被简单地忽略了。我检查了模型,发现我忘了在里面添加字段$fillable

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = ['name', 'email', 'password'];
Run Code Online (Sandbox Code Playgroud)

我添加了其他字段,它就像一个魅力。因此,如果有人遇到类似问题,解决方案非常简单,不要忘记填充$fillable数组;)