Laravel 模型中的默认 user_id 属性

ala*_*yli 1 laravel-5

我有一个模型

class Foo extends Model
{
    protected $fillable = [
        'name',
        'user_id'
    ];

}
Run Code Online (Sandbox Code Playgroud)

我想Auth::user()->id默认设置为user_id列。所以我补充说:

class Foo extends Model
{
    protected $fillable = [
        'name',
        'user_id'
    ];

    public function setUserIdAttribute()
    {
        $this->attributes['user_id'] = Auth::user()->id;

    }
}
Run Code Online (Sandbox Code Playgroud)

从我的控制器中,我Foo::create($data)没有user_id钥匙就打电话。但它没有按预期工作。因为缺少而store()给出。(用户已登录实现创建页面)Integrity constraint violationuser_id

小智 5

您提供了一个使用访问器的示例。

https://laravel.com/docs/5.1/eloquent-mutators#accessors-and-mutators

来自官方文档:

当尝试检索first_name的值时,Eloquent会自动调用该访问器:

如果你想为某些属性设置默认值,你需要使用观察者。

<?php
// file app/models/Foo.php
namespace App\Models;

use App\Observers\FooObserver;

class Foo extends Model
{
    protected $fillable = [
        'name',
        'user_id'
    ];

    public static function boot() {
        parent::boot();
        parent::observe(new FooObserver);
    }
}

<?php
// file app/observers/FooObserver.php
namespace App\Observers;

use App\Models\Foo;

class FooObserver {

    public function creating(Foo $model) {
        $this->user_id = Auth::user()->id;
    }
}
Run Code Online (Sandbox Code Playgroud)

关于官方文档中的模型观察者: https ://laravel.com/docs/5.0/eloquent#model-observers


K M*_*lom 5

我找不到有关model-observersLaravel 5.6 的官方文档。但是您仍然可以通过此代码来完成

public static  function boot()
{
    parent::boot(); // TODO: Change the autogenerated stub
    // it will automatically add authenticate user to created_by column of selected model 
    static::creating(function ($model){
        $model->created_by = auth()->user()->id;
    });
}
Run Code Online (Sandbox Code Playgroud)