Last active
October 26, 2020 07:50
-
-
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
This file contains hidden or 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
// 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