我的 Laravel 5.2 项目出现MethodNotAllowedHttpException
错误,而我正在添加“添加评论”部分。
这是我的路线:
Route::post('/posts/{post}/comments', 'CommentsController@store');
这是我的CommentsController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Comment;
use App\Http\Requests;
class CommentsController extends Controller
{
public function store(Post $post)
{
Comment::create([
'body' => request('body'),
'post_id' => $post->id
]);
return back();
}
}
这是我的观点:
@extends('layouts.master')
@section('content')
<div class="col-sm-8 blog-main">
<h1>{{ $post->title }}</h1>
{{ $post->body }}
<hr>
<h5>Comments</h5>
<div class="comments">
<ul class="list-group">
@foreach ($post->comments as $comment)
<li class="list-group-item">
<strong>
{{ $comment->created_at->diffForHumans() }}:
</strong>
{{ $comment->body }}
</li>
@endforeach
</ul>
</div>
<hr>
<!-- Add Comment -->
<div class="card">
<div class="card-block">
<form method="POST" action="/blog/public/posts/{{ $post->id }}/comments" >
<div class="form-group">
<textarea name="body" placeholder="Your Comment" class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Comment</button>
</div>
</form>
</div>
</div>
</div>
@endsection
变量$post
和$comment
成功传递到视图,因为检索内容和评论工作正常,但当我尝试提交新评论时,我得到MethodNotAllowedHttpException
。
答案 0 :(得分:1)
为您的路线提供名称
Route::post('/posts/{post}/comments', 'CommentsController@store')->name('comments.create');
添加csrf令牌并使用帮助方法route()
访问表单中的路径
<form method="POST" action="{{ route('comments.create', ['post' => $post->id]) }}" >
{{ csrf_field() }}
<div class="form-group">
<textarea name="body" placeholder="Your Comment" class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Comment</button>
</div>
</form>
更改您的功能签名
public function store($post)
{
Comment::create([
'body' => request('body'),
'post_id' => $post
]);
return back();
}
答案 1 :(得分:1)
您的表单操作应该是这样的
/posts/{{ $post->id }}/comments