Skip to content

Instantly share code, notes, and snippets.

@saber13812002
Last active October 26, 2020 07:50
Show Gist options
  • Save saber13812002/cbc2a4e8ffb1dc805cff4e1d80aa40de to your computer and use it in GitHub Desktop.
Save saber13812002/cbc2a4e8ffb1dc805cff4e1d80aa40de to your computer and use it in GitHub Desktop.
set all information of user or model to null after restore Laravel Setting null values only on certain fields
// BaseModel Class
protected $nullable = [];
/**
* Listen for save event
*/
protected static function boot()
{
parent::boot();
static::saving(function($model)
{
self::setNullables($model);
});
}
/**
* Set empty nullable fields to null
* @param object $model
*/
protected static function setNullables($model)
{
foreach($model->nullable as $field)
{
if(empty($model->{$field}))
{
$model->{$field} = null;
}
}
}
// In my model class, e.g. Comment
protected $nullable = ['post_id'];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment