Sunday, April 9, 2017

Laravel 5.4 save NULL to database not working

The following code results in an empty value inside the database and when I get it out of the database its an empty String.

$customer->update(['company' => NULL]);

SOLUTION

If you want a field inside the database to be null and you do not use a mutator everything is fine.

Are you using a mutator, in my case the following snippet.

public function setCompanyAttribute($value)
{
    $this->attributes['company'] = ucfirst($value);
}

Then you need to check if $value is null and then set it manually to null otherwise it will be an empty string.

To do that automatically on every model you can set the empty string back to null inside your EventServiceProvider.

Event::listen('eloquent.saving: *', function ($eventName, array $data) {
    $attributes = [];

    foreach ($data as $model) {
        foreach( $model->getAttributes() as $key => $value ) {
            $attributes[$key] = (is_string($value) && $value === '') ? null : $value;
       }

        $model->setRawAttributes($attributes);
    }

    return true;
});

It's important to first check all attributes from the model and set it to a temporary array. Now inside the setAttribute() method on the model instance the checks are done if a mutator exists. But thats exactly what you do not want, because it would set all fields with a definied mutator to an empty sting. Instead use setRawAttribute so the old attributes are overwritten with the ones from the temporary array.

This is save to do because if the checked value isn't an empty string the already existing value is taken for that field. Otherwise if it's an empty string then null is set.

Hope it helps!



via Ilario Engler

Advertisement