Laravel Cannot delete or update a parent row: a foreign key constraint fails
Clash Royale CLAN TAG#URR8PPP
Laravel Cannot delete or update a parent row: a foreign key constraint fails
For some reason a user cannot delete a post if it has been liked, it was working before but when I linked posts with likes I have been getting this error, I can't even delete it in Sequel Pro, unless I delete the likes associated with the post first.
Error
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or
update a parent row: a foreign key constraint fails
(eliapi8
.likes
, CONSTRAINT likes_post_id_foreign
FOREIGN KEY
(post_id
) REFERENCES posts
(id
)) (SQL: delete from posts
where
id
= 149)
eliapi8
likes
likes_post_id_foreign
post_id
posts
id
posts
id
Maybe it's my schema?
Posts Schema
Schema::create('posts', function (Blueprint $table)
$table->increments('id');
$table->string('title');
$table->text('body');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
);
Likes Schema
Schema::create('likes', function (Blueprint $table)
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
$table->foreign('user_id')->references('id')->on('users');
$table->softDeletes();
$table->timestamps();
);
I can like and unlike a post, but a user cannot delete a post that has been liked.
PostController.php
public function destroy(Post $post)
$this->authorize('delete', $post);
$postl = Post::with('likes')->whereId($post)->delete();
if ($post->delete())
if($postl)
return response()->json(['message' => 'deleted']);
;
return response()->json(['error' => 'something went wrong'], 400);
1 Answer
1
Yes, it's your schema. The constraint on likes.post_id
will prevent you from deleting records from the posts
table.
likes.post_id
posts
One solution could be using onDelete('cascade')
in the likes
migration file:
onDelete('cascade')
likes
Schema::create('likes', function (Blueprint $table)
// Some other fields...
$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.
$post->likes()->delete()
I updated the answer on why it wasn't possible to delete records from the
posts
table.– Camilo
Nov 29 '17 at 3:03
posts
thank you i love to learn
– BARNOWL
Nov 29 '17 at 3:43
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
it worked, so i can use onDelete if a post has likes.
– BARNOWL
Nov 29 '17 at 2:50