Reputation: 2948
I have two tables named user
and customer
.
Now how do I delete parent data when I delete child data?
Like when I run $customer->delete();
I want to delete from user
where user.id = customer.user_id
User model
use Illuminate\Auth\UserInterface;
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class User extends Eloquent implements UserInterface {
use SoftDeletingTrait;
protected $table = 'users';
public $timestamps = true;
protected $dates = ['deleted_at'];
}
Customer model
use Illuminate\Database\Eloquent\SoftDeletingTrait;
class Customer extends Eloquent {
/**
* The database table used by the model.
*
* @var string
*/
use SoftDeletingTrait;
protected $table = 'customers';
public $timestamps = true;
protected $dates = ['deleted_at'];
public function User(){
return $this->belongsTo('user','user_id','id');
}
}
Upvotes: 0
Views: 851
Reputation: 146191
There are Model Events are available in Eloquent
for this, for example:
class Customer extends Eloquent {
public static function boot()
{
parent::boot();
static::deleting(function($customer) {
// This will delete parent item
// before it deletes child item
$customer->user()->delete();
});
}
}
So, when you'll call something like this:
Customer::find(1)->delete();
The parent item User
will be deleted first then the child item Customer
will be deleted.
Upvotes: 1