laravel:在null上调用成员函数delete()
问题描述:
当我尝试通过单击删除按钮将删除功能添加到帖子时,出现了此错误. 我在哪里做错了?
I got this error when I tried to add a feature of delete, to the posts just by clicking on the delete button. Where am I doing wrong?
在PostController中删除发布函数:
Delete post function in PostController:
public function getDeletePost($post_id)
{
$post =Post::where('id',$post_id)->first();
$post->delete();
return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);
}
答
$post
object为null.也许您发送的是错误的$ post_id.如果您在删除之前检查帖子是否存在,则可以避免该错误.
$post
object is null. Maybe you are sending a wrong $post_id. If you check that the post exists before delete you avoid that error.
public function getDeletePost($post_id)
{
$post =Post::where('id',$post_id)->first();
if ($post != null) {
$post->delete();
return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);
}
return redirect()->route('dashboard')->with(['message'=> 'Wrong ID!!']);
}