我正在创建一个允许用户创建博客文章的laravel应用程序。
我创建了一个PostsController作为具有存储函数的资源,如下所示:
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required'
]);
return 123;
}
另外,我在web.php中添加了一个路由
Route::resource('posts', 'PostsController');
如果我用php artisan php artisan show:routes
列出路线,则会列出POST方法:
HTML表单如下所示:
<form action="PostsController@store" method="POST">
<div class="form-group">
<label for="title">Title</label>
<input class="form-control" type="text" id="title">
</div>
<div class="form-group">
<label for="body">Body</label>
<textarea class="form-control" id="body" rows="3"></textarea>
</div>
<input type="submit" class="btn btn-primary">
</form>
当我提交表单时,我得到MethodNotAllowedHttpException:
The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE.
我之前习惯使用laravel集体表单。没有在laravel做过一段时间的任何工作,现在它似乎被弃用(https://laravelcollective.com/),所以我使用经典的HTML表单。我该如何解决这个问题?
您的表单中的操作不正确 - 您需要将操作指向路径的URL,然后路由将选择方法,在本例中为“store”方法。另外,请添加@csrf
以获取更多信息CSRF Protection
<form action="{{ route('posts.store') }}" method="POST">
@csrf
<div class="form-group">
<label for="title">Title</label>
<input class="form-control" type="text" id="title">
</div>
<div class="form-group">
<label for="body">Body</label>
<textarea class="form-control" id="body" rows="3" name="body"></textarea>
</div>
<input type="submit" class="btn btn-primary">
</form>
在textbox和textarea中添加名称
form action="{{ route('posts.store') }}" method="POST">
@csrf
<div class="form-group">
<label for="title">Title</label>
<input class="form-control" type="text" id="title" name="title">
</div>
<div class="form-group">
<label for="body">Body</label>
<textarea class="form-control" id="body" rows="3" name="body"></textarea>
</div>
<input type="submit" class="btn btn-primary">
</form>