'How to delete data with foreign key?

I need some help to delete a movie from my database.

I know that since I have pivot tables I will get some troubles with foreign key(my delete controller gives this error), but I don't know how to solve it.

The error i'm getting is the following: SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (sakila.film_category, CONSTRAINT fk_film_category_film FOREIGN KEY (film_id) REFERENCES film (film_id) ON UPDATE CASCADE) (SQL: delete from film where film_id = 999)

My database tables

Here are my models:

model Film:

class film extends Model{
    protected $table = "film";  
    protected $primaryKey = 'film_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['film_id', 'title', 'length'];

    public function category(){
        return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id');
    }        
    public function actor(){
              return $this->belongsToMany(actor::class,'film_actor', 'film_id', 'actor_id');
    }    
} 

model Category:

class category extends Model{
    protected $table = "category";
    protected $primaryKey = 'category_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['category_id','name'];

    public function film(){
        return $this->belongsToMany(film::class,'film_category', 'category_id', 'film_id');
    }
}

model Actor:

class actor extends Model{
    protected $primaryKey = 'actor_id';
    public $timestamps = false;
    use HasFactory;
    protected $sql=['actor_id', 'first_name', 'last_name'];

    public function film(){
          return $this->belongsToMany(film::class,'film_actor', 'actor_id', 'film_id');
      }
}

Now I need some help to make my controller function to delete records.

 public function remove($film_id){
        $film=film::findOrFail($film_id);
        $film->delete();
        
        return redirect('/film/view');

Thanks



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source