发布于 5年前

Laravel - Method delete does not exist

报错:BadMethodCallException in Macroable.php line 74: Method delete does not exist.

route:

Route::resource('posts', 'PostController');

my controller:

public function destroy($id)
{
    $user_id = Auth::user();
    $post= Post::where('id', $id)->where('user_id',$user_id)->get();
    $post->delete();

    return view('/home', [
        'posts' => $post
    ]);
}

view:

  <form action="{{ route('posts.destroy', '$post->id') }}" method="post">
  <input type="hidden" name="_method" value="DELETE" />
      {{ csrf_field() }}
       {{ method_field('DELETE') }}

   <input type="submit" class="btn btn-danger" value="delete" />
  </form>

尝试改为 method="post",不报错但也没删除。

解决方案:

去除 get() 就能正常了。如下:

$post= Post::where('id', $id)->where('user_id',$user_id);
$post->delete();

如果你想删除结果中的第一个:

$post= Post::where('id', $id)->where('user_id',$user_id)->first();
$post->delete();

但是在删除时你需要检查 $post 是否存在:

if($post){
    $post->delete();
} 
©2020 edoou.com   京ICP备16001874号-3