Laravel Eloquent ignore attribute if not in table during insert

前端 未结 4 1444
不思量自难忘°
不思量自难忘° 2021-02-19 03:44

I have a model Foo that corresponds to a table with the following columns.

id
description
user_id

I\'m setting the attributes of the Foo model individual

4条回答
  •  南旧
    南旧 (楼主)
    2021-02-19 04:25

    I know it is too late, but you can register the saving operation by override the boot function in your model:

    protected static function boot() {
        parent::boot();
    
        static::saving(function($model) {
            $savable = [...];
            if (count($savable) > 0) {
                $model->attributes = array_intersect_key($model->attributes, array_flip($savable));
            }
        });
    }
    

    This is untested code, but the idea is to remove the attributes that have not intersect with the variable savable before saving the model. The variable savable is an array of the savable attributes. For example $savable = ['foo', 'bar'] will save only the foo and bar attributes.

    Pros: You can mass assign any attributes that you want without harm to fillable or guarded.

    Cons: The attributes that are not marked as savable, will be deleted from the model after saving.

提交回复
热议问题