Laravel 5: How to get remote related models?

I have the following models; Brand, Image and Image_size. A brand has one image, and an image has many images. All of these models use soft deletions, and the deleted aspect is fine. However, if I wanted to restore the deleted brand, I also need to restore the associated image models and image_size.

I study model events, so when my brand model is restored, I can get the image and restore it, and then I will have a similar event in the image model to get the image sizes and restore those. I am trying to get a record of deleted images, though for a brand. This is what I am trying to do in my brand model:

/** * Model events */ protected static function boot() { parent::boot(); /** * Logic to run before delete */ static::deleting(function($brand) { $brand->image->delete(); }); /** * Logic to run before restore */ static::restoring(function($brand) { $brand = Brand::withTrashed()->with('image')->find($brand->id); $brand->image->restore(); }); } 

I get the following error message on a line that is trying to restore the image:

 Call to a member function restore() on a non-object 
+6
source share
1 answer

In your code, you turn off the soft deletion restriction in the query that retrieves the brand, not the image. Try the following:

 static::restoring(function($brand) { $brand->image()->withTrashed()->first()->restore(); }); 

Note that there is no need to retrieve the $ brand object when it automatically passed the callback.

+4
source

All Articles