Laravel Eloquent ignores attribute if not in table at insert time

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

ID
description
user ID

I set Foo model attributes individually (without bulk assignment)

$foo = new Foo; $foo->id = 1; $foo->description = "hello kitty"; $foo->user_id = 55; //... 

$ foo is sent to another class for additional processing, but since this class needs a bit more information, I would just like to add it to the $ foo model.

 //... $foo->bar = $additional_information; Event::fire(DoStuffWithFoo($foo)); $foo->save(); //error 

The problem is that when I $foo->save() , it complains that bar not a column.

I know I can unset($foo->bar); before saving, but ...

Is it possible to tell Eloquent to simply ignore any irrelevant attributes?

+6
source share
2 answers

I know that it's already too late, but you can register the saving operation by overriding 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 attributes that do not intersect with the savable variable before saving the model. The savable variable is an array of savable attributes. For example, $savable = ['foo', 'bar'] only save the foo and bar attributes.

Pros: you can massively assign any attributes you want, without prejudice to fillable or guarded .

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

+1
source

Add $ fillable, and the model will ignore everything that is not in it (instead of giving an error). Using the constructor function to fill all columns is optional.

 class Foo extends Model { protected $fillable = ['id', 'description', 'user_id']; } $f = new Foo(['id' => 1, 'description' => "hello monkey", 'user_id' => 55, 'bar' => 'wow']); // should work w/o error, but it ignores the 'bar'. 
0
source

All Articles