Latest

Tuesday, July 11, 2017

How to save a model with custom attributes that are not in the database? - Laravel 5.4

Asked by: Tim van Uum


I have a situation where I have set some custom attributes on a model. These attributes don't exist in the database. When using ->isDirty() on the model I get the custom attributes that don't belong in the database.

Is there some clean way to remove these attrbiutes before saving the model?

$model = SomeModel::find(1);
$model->database_attribute = 'I exists in the database';
$model->custom_not_in_database_attribute = 'I don\'t exists in the database';
$model->save(); // remove dirty on save?!

I can of course just unset them unset($model->custom_not_in_database_attribute), but I like to know if there is a cleaner way to do this?

Something like (not existing) $model->saveOriginalOnly()


Answers

Answered by: sam12 at 2017-07-11 01:47PM Accepted



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);


Answered by: Tim van Uum at 2017-07-11 05:29PM



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;
}



Source

No comments:

Post a Comment

Adbox