Skip to content

Instantly share code, notes, and snippets.

@yilmazerhakan
Created October 14, 2018 10:31
Show Gist options
  • Save yilmazerhakan/1e2d8590689cb05d3dbd1009145722e8 to your computer and use it in GitHub Desktop.
Save yilmazerhakan/1e2d8590689cb05d3dbd1009145722e8 to your computer and use it in GitHub Desktop.
Consisted Restore of Soft Deleted Models with Relations in Laravel
<?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