晚上好,上学时,我正在尝试使用laravel 6和mongoDB创建一个简单的CRUD应用。
我可以读取,更新和删除工作,但是创建失败,此路由不支持POST方法。支持的方法:GET,HEAD ..我已经在这里和其他网站上搜索了答案,但是我停留了2天(可能有些愚蠢,但是我看不到它)
我的路线是:
Route::get('/home', 'HomeController@index')->name('home');
Route::get('/post/{_id?}', 'PostController@form')->name('post.form');
Route::post('/post/save/', 'PostController@save')->name('post.save');
Route::put('/post/update/{_id}', 'PostController@update')->name('post.update');
Route::get('/post/delete/{_id}', 'PostController@delete')->name('post.delete');
form.blade是:
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Post Form</div>
<div class="card-body">
@if($data)
<form action = "{{Route ('post.update', $data->_id)}}" method="post">
@csrf
@method('PUT')
<div class="form-group">
<label for="usr">Title:</label>
<input type="text" class="form-control" name="title" value = "{{$data->title}}" >
</div>
<div class="form-group">
<label for="comment">Content:</label>
<textarea class="form-control" rows="5" name="content">{{$data->content}}</textarea>
</div>
<p align="center"> <button class="btn btn-primary">save</button></p>
</form>
@else
<form action = "{{Route ('post.form')}}" method="post">
@csrf
<div class="form-group">
<label for="usr">Title:</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="comment">Content:</label>
<textarea class="form-control" rows="5" name="content"></textarea>
</div>
<p align="center"> <button class="btn btn-primary">save</button></p>
</form>
@endif
</div>
</div>
</div>
</div>
@endsection
我的PostController是:
<?php
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
//
public function form($_id = false){
if($_id){
$data = Post::findOrFail($_id);
}
$data = false;
return view ('post.form', compact('data'));
}
public function save (Request $request){
$data = new Post($request->all());
$data->save();
if($data){
return redirect()->route('home');
}else{
return back();
}
}
public function update (Request $request, $_id){
$data = post::findOrFail($_id);
$data->title = $request->title;
$data->content = $request->content;
$data->save();
/* return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]); */
if($data){
return redirect()->route('home');
}else{
return back();
}
}
public function delete($_id){
$data = post::destroy($_id);
if($data) {
return redirect()->route('home');
}
else {
dd('error cannot delete this post');
}
}
}
有人知道我想念什么吗?
预先感谢
答案 0 :(得分:3)
您必须将此行<form action = "{{Route ('post.form')}}" method="post">
替换为<form action = "{{Route ('post.save')}}" method="post">
答案 1 :(得分:1)
您使用的路线错误。请更改为Route ('post.save')
答案 2 :(得分:0)
编辑:我发现自己一个人,如果有$ _id,PostControler不会返回视图
感谢大家的帮助! 感谢您指出这一点,它的确使我复活了:)但是它破坏了更新功能:S。
当我现在单击“编辑”按钮时,表单不再填充该帖子的数据,并且“保存”将创建一个新帖子,而不是对其进行更新。