Laravel Cannot delete or update a parent row: a foreign key constraint fails

Yes, it’s your schema. The constraint on likes.post_id will prevent you from deleting records from the posts table.

One solution could be using onDelete('cascade') in the likes migration file:

Schema::create('likes', function (Blueprint $table) {
    $table->integer('post_id')->unsigned();
    $table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
});

This way, when a post is deleted, all related likes will be deleted too.

Or, if you have a relationship from the Post model to the Like model, you can $post->likes()->delete() before deleting the post itself.

Leave a Comment