Laravel Eloquent ORM - removing rows and all the child relationship, with event deleting
Solution 1
Just a quick recap:
$model->related_model
will return the related model.
$model->related_model()
will return the relation object.
You can do either $model->related_model->delete()
or $model->related_model()->get()->delete()
to access the delete()
method on the model.
Another way of handling the deletion of related (or sub) models is to use foreign key constraints when you write your migrations, check https://laravel.com/docs/master/migrations#foreign-key-constraints
Solution 2
I think you can do this in the delete function of the parent object:
public function destroy_parent($id)
{
$parent = PARENT::find($id);
foreach ($parent->childs as $child){
$child->delete();
}
$parent->delete();
return redirect(...);
}
Kamol Hakimbaev
Updated on June 19, 2022Comments
-
Kamol Hakimbaev almost 2 years
I have three models that relate to each other one to many:
Country
class Country extends Model { protected $fillable=['name','sort']; public $timestamps=false; public function region(){ return $this->hasMany('App\Models\Region'); } }
Region
class Region extends Model { protected $fillable=['country_id','name','sort']; public $timestamps=false; public function country() { return $this->belongsTo('App\Models\Country'); } public function city() { return $this->hasMany('App\Models\City'); } }
City
class City extends Model { protected $table='cities'; protected $fillable=['region_id','name','sort']; public $timestamps=false; public function region() { return $this->belongsTo('App\Models\Region'); } }
When we remove the country automatically, remove all child item relationship, that is, removed and regions and city this country
I am doing so:
Model Country
public static function boot() { parent::boot(); static::deleting(function($country) { //remove related rows region and city // need an alternative variation of this code $country->region()->city()->delete();//not working $country->region()->delete(); return true; }); } }
OR
Model Region
public static function boot() { parent::boot(); // this event do not working, when delete a parent(country) static::deleting(function($region) { dd($region); //remove related rows city $region->city()->delete(); return true; }); } }
options with cascading deletes database, please do not offer
UPDATE
I found the answer
use closure for query builder, to remove related models
Model Country
public static function boot() { parent::boot(); static::deleting(function($country) { //remove related rows region and city $country->region->each(function($region) { $region->city()->delete(); }); $country->region()->delete();// return true; }); }
Laravel Eloquent ORM - Removing rows and all the inner relationships