Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: How to retrieve deleted related models?

I have the following models; Brand, Image, and Image_size. Brand has one image and image has many image_sizes. All of these models use soft deletes and the deleting aspect is fine. However if I then wanted to restore a brand that has been deleted I also need to restore the related image and image_size models.

I have been looking into using model events so that when my Brand model is being restored I can get the image and restore that, and then I'll have a similar event in the image model to get the the image sizes and restore those. I'm struggling to get the deleted image record though for the brand. This is what I have 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 just get the following error message on the line that tries to restore the image:

Call to a member function restore() on a non-object
like image 709
geoffs3310 Avatar asked Jul 09 '15 08:07

geoffs3310


1 Answers

In your code you disable soft delete constraint on the query that fetches the brand, not the image. Try the following:

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

Please note that there is no need to fetch the $brand object as it's passed to the restoring callback automatically.

like image 155
jedrzej.kurylo Avatar answered Sep 25 '22 01:09

jedrzej.kurylo