Welcome, I hope my blog is of some use for you!

Laravel

Save a model with custom attributes – Laravel 5.4+

I had a situation where I have custom attributes on one of my models. These attributes didn’t exist in the database. So how could I save this model without manually remove all these attributes. When using ->isDirty() on the model I get the custom attributes that don’t belong in the database. But at first I couldn’t figure out how to use that. After trying some things out I came up with this solution.

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

If you apply this method to a base model you can now easily save a model with custom attributes! What this method does is it checking what attributes didn’t came from the database and are dirty. Next it loops through the attributes and checks if the attribute is not in the original attributes. If not then it will unset this specific attribute.

Next it will save the model and after it is saved it loops through the dirty attributes and re-adds them to the model. So we have our original model back again and no data is lost.

I once had this same problem and tried many things out even asked it on stackoverflow. But there was no great solution until I came up with this.

Related posts
Laravel

No more helper functions for Laravel?

Laravel

Translatable resource routes in Laravel

Laravel

Force deleting event in Laravel

Laravel

How to set logout redirect path in laravel 5.3+

Sign up for our Newsletter and
stay informed

Leave a Reply

Your email address will not be published. Required fields are marked *