Skip to content

Instantly share code, notes, and snippets.

@ipanardian
Created April 2, 2019 03:02
Show Gist options
  • Save ipanardian/dcf122e41ea079e025c656fdb6f2adb6 to your computer and use it in GitHub Desktop.
Save ipanardian/dcf122e41ea079e025c656fdb6f2adb6 to your computer and use it in GitHub Desktop.
Convert null value from database to empty string for response
<?php
namespace App\Traits;
/**
* Convert null value from database to empty string for response
*
* Usage:
* use Illuminate\Database\Eloquent\Model;
* use App\Traits\NullToEmptyString;
*
* class Order extends Model
* {
* use NullToEmptyString;
*
* ....
* }
*/
trait NullToEmptyString
{
public static function bootNullToEmptyString()
{
static::retrieved(function($model) {
foreach ((array) $model->fillable as $key) {
if ($model->getAttribute($key) === null) {
$model->attributes[$key] = '';
}
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment