Created
October 14, 2018 10:31
-
-
Save yilmazerhakan/1e2d8590689cb05d3dbd1009145722e8 to your computer and use it in GitHub Desktop.
Consisted Restore of Soft Deleted Models with Relations in Laravel
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\Models; | |
use Illuminate\Database\Eloquent\Model; | |
use Illuminate\Database\Eloquent\SoftDeletes; | |
class Users extends Model | |
{ | |
use SoftDeletes; | |
protected $dates = ['deleted_at']; | |
/** | |
* Override parent boot and Call deleting event | |
* | |
* @return void | |
*/ | |
protected static function boot() | |
{ | |
parent::boot(); | |
static::deleted(function ($users) { | |
$users->posts()->delete(); | |
}); | |
static::restoring(function($users) { | |
$users->posts()->withTrashed()->where('deleted_at', '>=', $users->deleted_at)->restore(); | |
}); | |
} | |
/** | |
* a user has many posts. | |
*/ | |
public function posts() | |
{ | |
return $this->hasMany(Posts::class, 'post_id'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment