Onyx
Onyx

Reputation: 67

How can I delete a foreign key based record upon deletion of an image?

After I delete a record from my images table, I am left with a record in my tag_image table that connects an image that doesn't exist anymore to a tag. I would like to somehow remove that connection when I am deleting the image.

Table: images
Columns: id, Title, Path

Table: tags
Columns: id, name

Table: tag_image
Columns: image_id, tag_id

My deleteImage function:

public function deleteImage($imageId){
        $image = Image::where('id', $imageId)->first();
        if (!Auth::user()->hasRole('Admin')) {
            if (Auth::user() != $image->user){
                return redirect()->back();
            }
        } else if (Auth::user()->hasRole('Admin')) {
            $imageName = $image->file_name;
            $image->delete();
            Storage::delete('public/images/uploaded/'.$imageName);
            return redirect()->route('home');
        }
        $imageName = $image->file_name;
        $image->delete();
        Storage::delete('public/images/uploaded/'.$imageName);
        return redirect()->route('home');
    }

tag model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tag extends Model
{
    public function images(){
        return $this->belongsToMany('App\Image', 'tag_image','tag_id','image_id');
    }
}

image model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Image extends Model
{
    public function user(){
        return $this->belongsTo('App\User');
    }

    public function tags(){
        return $this->belongsToMany('App\Tag','tag_image','image_id','tag_id');
    }
}

Upvotes: 0

Views: 91

Answers (2)

caiolopes
caiolopes

Reputation: 571

If you are using migrations, you can do in your relationship model:

$table->foreign('image_id')
      ->references('id')->on('image')
      ->onDelete('cascade');

Or even directly in the database you can define a delete cascade relationship.

ALTER TABLE image_tag
   ADD CONSTRAINT `fk_image`
   FOREIGN KEY (`image_id`)
   REFERENCES `image` (`id`)
   ON DELETE CASCADE

More on migrations:

https://laravel.com/docs/5.6/migrations

Upvotes: 1

Mohammad Fanni
Mohammad Fanni

Reputation: 4173

You should detach before you delete like this

$image = Image::where('id', $imageId)->first();
$image->tags()->detach();

or

$image->tags()->detach($tag_id);

Reading Material

Inserting and Updating Related Models

Upvotes: 1

Related Questions