【问题标题】:Laravel Eloquent Model pass only certain parametersLaravel Eloquent 模型仅传递某些参数
【发布时间】:2017-04-20 02:06:34
【问题描述】:

在我的Users 模型上,它只能接受某些列吗?

就像我传递用户名、电子邮件和密码一样,在 Users 模型上,它将过滤为仅接受用户名和密码。

我尝试填写protected $fillable = ['username','password'];,但似乎不起作用。

【问题讨论】:

  • 你怎么了?你能显示任何错误吗?
  • 你的模型中有protected $guarded = [];吗??

标签: php laravel model eloquent lumen


【解决方案1】:

这取决于数据库中用户模型的架构。 laravel 中包含用户表的迁移文件,如果您运行了 php artisan migrate,这应该在数据库中。以下是 Laravel 附带的迁移文件的一部分(位于 database/migrations/ 中):

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

您可以看到默认情况下您只能填写三列,如果需要,您可以在此处添加更多。尽管您需要在对迁移文件进行更改之前运行 php artisan migrate:rollback 然后再次运行 php artisan migrate。 (https://laravel.com/docs/5.4/migrations)

受保护的 $fillable 数组只选择可以批量分配的属性 (https://laravel.com/docs/5.4/eloquent#mass-assignment),因此如果您想使用这样的静态创建方法,您将需要这些:

User::create(['name' => 'John Doe', 'email' => 'john@doe.com, 'password' => bcrypt('password')]);

【讨论】:

    猜你喜欢
    • 2015-03-28
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 2017-01-19
    • 2017-06-22
    • 1970-01-01
    相关资源
    最近更新 更多