How to save a model with custom attributes that are not in the database? - Laravel 5.4
You can use getAttributes() and getOriginal() like this :
$model=Model::findOrFail($id);
$model->new='new';
foreach ($model->getAttributes() as $key => $value) {
if(!in_array($key, array_keys($model->getOriginal())))
unset($model->$key);
}
dd($model);
An easier way to do is just to add this property as a model's property like this:
class Land extends Eloquent {
public $thisFieldWontBeSavedInDatabase;
//...
}
and it's done.
With this simple declaration, eloquent won't trigger the __set() method to add to the $attributes property. And only the fields in the $attributes property are saved in the database.
The full solution for me was adding this method to the custom base model. It saves the original fields. But keeps the custom attributes.
public function saveOriginalOnly()
{
$dirty = $this->getDirty();
foreach ($this->getAttributes() as $key => $value) {
if(!in_array($key, array_keys($this->getOriginal()))) unset($this->$key);
}
$isSaved = $this->save();
foreach($dirty as $key => $value) {
$this->setAttribute($key, $value);
}
return $isSaved;
}
See also: https://codeneverlied.com/how-to-save-a-model-with-custom-attributes-that-are-not-in-the-database-laravel-5-4/