Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 使用Laravel Eloquent自动设置属性_Php_Laravel_Eloquent_Model - Fatal编程技术网

Php 使用Laravel Eloquent自动设置属性

Php 使用Laravel Eloquent自动设置属性,php,laravel,eloquent,model,Php,Laravel,Eloquent,Model,我有一些属性,在使用create()或save()方法时需要自动设置 型号: 控制器 我需要保存random\u列值,如您所见,该值在模型本身中定义,而无需从控制器传递它 请注意,如果我使用: SampleModel::create([ 'name' => 'Jeff', 'random_column' => true // or anything other than string ]); 它可以工作并设置值,但是

我有一些属性,在使用
create()
save()
方法时需要自动设置

型号: 控制器 我需要保存
random\u列
值,如您所见,该值在模型本身中定义,而无需从控制器传递它

请注意,如果我使用:

    SampleModel::create([
        'name'          => 'Jeff',
        'random_column' => true // or anything other than string
    ]);

它可以工作并设置值,但是有没有办法避免每次都传递该值,而只是在模型中自动设置它?

您尝试过吗?将
boot()
方法添加到您的
SampleModel

protected static function boot()
{
    parent::boot();
    static::creating(function (SampleModel $model) {
        $model->random_column = 'Random column';
    });
}

每次对
SampleModel

调用
->create()
时,Creating都将触发该操作。您是否尝试过?将
boot()
方法添加到您的
SampleModel

protected static function boot()
{
    parent::boot();
    static::creating(function (SampleModel $model) {
        $model->random_column = 'Random column';
    });
}

每次对
SampleModel

调用
->create()
时,Creating都会触发。谢谢,使用
$model->save()
时,我遇到了以下错误:
函数嵌套级别达到最大值“256”,正在中止但是现在您删除了它,它工作得非常好!谢谢,使用
$model->save()
时,我遇到了以下错误:
函数嵌套的最大级别达到了“256”,正在中止但是现在您删除了它,它工作得非常好!
protected static function boot()
{
    parent::boot();
    static::creating(function (SampleModel $model) {
        $model->random_column = 'Random column';
    });
}