Created
April 2, 2019 03:02
-
-
Save ipanardian/dcf122e41ea079e025c656fdb6f2adb6 to your computer and use it in GitHub Desktop.
Convert null value from database to empty string for response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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