在 laravel 中调用创建新外观实例的函数

Call a function on creation of new facade instance in laravel

基本上假设我有一个名为 'Window' 的模型。我知道 laravel 为模型的新实例提供了创建的事件,问题是我并不总是先创建新的数据库记录以便调用该方法,但有时我需要先创建外观的实例。我的意思是:

$window = App\Window::create(); //this creates a new record in the 
//database and the 'created' event is being called in laravel, 
//so I can assign some properties. Everything is ok
$window = new App\Window;//but this only creates an instance of the facade 
//which is not being saved until `$window->save();` is called.

问题是,到目前为止,在我的代码中我避免直接​​在数据库中创建新的空记录,所以我使用了第二种方法。但现在我想处理 new App\Window 的创建,以便以编程方式为每个 window 分配自定义默认属性。有办法实现吗?

这应该有效。如果默认值尚未传入,它只会应用默认值。我还将默认值设置为常量,因此如果您以后需要修改它们,它们很容易找到。

const COLUMN_DEFAULT = 'some default';

const SOME_OTHER_COLUMN_DEFAULT = 'some other default';

public function __construct(array $attributes = [])
{
    if (! array_key_exists('your_column', $attributes)) {
        $attributes['your_column'] = static::COLUMN_DEFAULT;
    }

    if (! array_key_exists('some_other_column_you_want_to_default', $attributes)) {
        $attributes['some_other_column_you_want_to_default'] = static::SOME_OTHER_COLUMN_DEFAULT;
    }

    parent::__construct($attributes);
}

你可以的

new Window($request->all());
// Or
new Window($request->only(['foo', 'bar']));
// Or immediately create the instance
Window::create($request->all());

但是你应该首先将需要的属性添加到 Window 模型中的 $fillable 属性

class Window extends Model {
    protected $fillable = ['foo', 'bar'];
}