Search code examples
ormlaravellaravel-4relational-model

Laravel relational delete between three models


I have a simple relational models that I've built like that : Parent :

    <?php

    class Appartement extends Eloquent {

        public function gallery()
        {
            return $this->hasOne('Gallery', 'object_id')->where('type', '=', 'appartement');
        }

        public function delete()
        {
            $this->gallery()->delete();
            return parent::delete();
        }
    }

First children Gallery

    class Gallery extends \Eloquent {
        protected $fillable = [];

        public function images()
        {
            return $this->hasMany('GalleryImage');
        }

        public function delete()
        {
            $this->images()->delete();
            return parent::delete();
        }
    }

Second Children Images

    class GalleryImage extends \Eloquent {
        protected $fillable = [];

        public function gallery()
        {
            return $this->belongsTo('Gallery');
        }

        public function delete()
        {
            unlink(public_path().$this->link);
            return parent::delete();


        }
    }

So basically nothing big : One appartement has one gallery, one gallery has many images. It works pretty well, the problem is that when I delete an appartement, I would like to delete the gallery and the images associated to the appartement.

So I've tried to override the delete method. Appartement get deleted, as well as gallery, but the images are not deleted, and it seems that there is no access to the delete function of Gallery, because I've tried to add a die; in the function, but it never dies.

Does anyone know how I can overcome this ? Thanks


Solution

  • You have 2 options, the first is to set up foreign key constraints and cascade on delete using your migrations

    // gallery migration
    DB::table('galleries', function($table){
        $table->foreign('object_id')
            ->references('id')->on('appartments')
            ->onDelete('cascade');   
    });
    
    // images migration
    DB::table('images', function($table){
        $table->foreign('gallery_id')
            ->references('id')->on('galleries')
            ->onDelete('cascade');   
    });
    

    The other option is to use model observers here is an example: http://www.laravel-tricks.com/tricks/cascading-deletes-with-model-events this is useful on DB's that don't support FK constraints.