Parent child soft deleting is simple but when the scenario is extended to children of the child to be deleted from the parent model I'm finding it uncomfortable. This image describes fully the relationship I'm trying to cope with
I have a company that has address and product as children. Deleting these is convenient using soft delete. Product, as the child of company has it child which is address, what I want to achieve is when a company is deleted this product address should also be deleted. This is my company model:
class Company extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
public function products()
{
return $this->hasMany('App\Product');
}
public function companyAddress()
{
return $this->hasMany('App\CompanyAddress');
}
public function delete()
{
$product = new Product;
$this->products()->delete();
$this->companyAddress()->delete();
$product->productLocation()->delete();
return parent::delete();
}
}
THis is the product model:
class Product extends Model
{
public function productLocation()
{
return $this->hasMany('App\ProductLocation');
}
public function delete()
{
$this->productLocation()->delete();
return parent::delete();
}
}
This is the function in the controller where the deletion is done:
public function destroy($id)
{
$company = Company::findOrFail($id);
if(!$company->user_id === Auth::user()->id)
{
return redirect()->route('companyindex')->with('message', 'Sorry, you cannot delete this company');
}else{
$company->delete();
return redirect()->route('companyindex')->with('message', 'Company successfully deleted.');
}
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire