Search code examples
phpdatabaselaravelequivalent

Convert NULL into empty string while getting response


i just want how can we convert null into empty string while getting result from db. For example

User::first();

In user table, roll number is null value. i want it to convert into empty string.


Solution

  • Yes, you can do this in boot method with retrieved observer like this.

     self::retrieved(function ($model) {
            $keys = $model->fillable;
            foreach ($keys as $key => $value) {
                $model->attributes[$value] = @$model->attributes[$value] == null ?  '' : $model->attributes[$value];
            }
        });