laravel:在null上调用成员函数delete()

时间:2016-11-04 11:22:49

标签: laravel

当我尝试通过单击删除按钮向帖子添加删除功能时,我收到此错误。 我在哪里做错了?

删除PostController中的帖子功能:

public function getDeletePost($post_id)
{
    $post =Post::where('id',$post_id)->first();
    $post->delete();
    return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);
} 

4 个答案:

答案 0 :(得分:4)

$post对象为空。也许你发错了$ post_id。如果在删除之前检查帖子是否存在,则可以避免该错误。

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!!']);
} 

答案 1 :(得分:2)

看起来你没有Post id = $post_id,你可以尝试使用firstOrFail方法:

public function getDeletePost($post_id)
{
    $post =Post::where('id',$post_id)->firstOrFail();
    $post->delete();
    return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);
}

或开始使用Route Model Binding,然后您不需要关心Post是否存在id = $post_id

首先,您需要在RouteServiceProvider::boot

中添加绑定
$router->model('post', 'App\Post');

然后在路线中你需要改变这个:

Route::post('post/{post}/delete', [
    'as' => 'post.delete', 'uses' => 'PostController@getDeletePost'
]);

然后你的控制器看起来像这样:

public function getDeletePost(Post $post)
{
    $post->delete();
    return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);
}

如果您仍然有问题,您应该向我们展示如何构建向控制器发送请求的POST表单。

答案 2 :(得分:1)

您的$ post变量有可能为null / undefined。

public function getDeletePost($post_id) {
  try {
    $post = Post::where('id',$post_id)->first();
  } catch (ModelNotFoundException $e) {
    return redirect()->route('dashboard')->with(['message'=> 'Failed']);
  }

  $post->delete();

  return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);
} 

答案 3 :(得分:0)

你雄辩的查询没有返回结果,所以$ post变量为空,导致错误。

而是使用findOrFail,如果找不到提供id的记录,则会抛出异常。

$post = Post::findOrFail($id);
$post->delete();
return redirect()->route('dashboard')->with(['message'=> 'Successfully deleted!!']);

如果抛出了ModelNotFound异常,那么这意味着在提供的Id的数据库中不存在Post记录。