我正在创建一个允许用户创建博客文章的 Laravel 应用程序。
我创建了一个 PostsController 作为具有 store 功能的资源,如下所示:
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'body' => 'required'
]);
return 123;
}
Run Code Online (Sandbox Code Playgroud)
另外,我在 web.php 中添加了一个路由
Route::resource('posts', 'PostsController');
Run Code Online (Sandbox Code Playgroud)
如果我使用 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>
Run Code Online (Sandbox Code Playgroud)
当我提交表单时,我收到 MethodNotAllowedHttpException:
The POST method is not supported for this route. Supported methods: GET, HEAD, PUT, PATCH, DELETE.
我以前曾经使用 laravel 集合体作为表单。有一段时间没有在 laravel 中做任何工作,现在它似乎已被弃用(https://laravelcollective.com/),所以我求助于经典的 HTML 表单。我该如何解决这个问题?
您的操作在表单中不正确 - 您需要将操作指向路由的 URL,然后路由将选择方法,在本例中为“存储”方法。还添加@csrf了更多信息CSRF 保护
<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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3712 次 |
| 最近记录: |