我找不到问题。它显示404 |未找到
update.blade.php
@extends('main')
@section('content')
<h1>Update Post</h1>
<form method="POST" action="{{route('posts.update', $post) }}" >
@method('PUT')
@csrf
<input type="text" name="title"><br><br>
<input type="text" name="body"><br><br>
<button type="submit" class="btn btn-primary">Update</button>
</form>
@endsection
PostController.php(资源控制器)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\posts;
use Sessions;
class PostController extends Controller
{
public function index()
{
$post = posts::all();
return view('post.index', compact('post');
}
public function create(Request $req)
{
return view('posts.create');
}
public function store(Request $request)
{
$post = new posts;
$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
return redirect('/');
}
public function show($data)
{
$post = posts::findOrFail($data);
return view('posts.read', compact('post','$post'));
}
public function edit(posts $post)
{
return view('posts.edit', compact('post'));
}
public function update(Request $request, $id)
{
$request->validate([
'title'=>'required',
'body'=>'required'
]);
$post = posts::find($id);
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->save();
return redirect('/');
}
}
路线:
Route::resource('posts', 'PostController');
请告诉我这是什么问题。 我得到的建议之一是更改视图文件的名称,即将update.blade.php更改为edit.blade.php。我不知道有什么帮助
答案 0 :(得分:1)
问题是您要返回视图:view('post.edit')
。
但是您说该文件名为update.blade.php
。
因此,您必须将文件重命名为edit.blade.php
,或者,您需要按以下方式更改编辑功能,以便它返回更新刀片文件:
public function edit(posts $post)
{
return view('posts.update', compact('post'));
}
答案 1 :(得分:0)
首先,您应该更改edit.blade.php
而不是update.blade.php
第二,您不应该像这样use App/posts;
调用模型。这是错误的。它必须是use App\Post;
中的PostController
第三,您应该在控制器中更改edit()
public function edit($id)
{
$post = Post::find($id);
return view('posts.edit', compact('post'));
}
您应在表单操作中使用$post->id
而不是$post
@extends('main')
@section('content')
<h1>Update Post</h1>
<form method="POST" action="{{route('posts.update', $post->id) }}" >
@method('PUT')
@csrf
<input type="text" name="title"><br><br>
<input type="text" name="body"><br><br>
<button type="submit" class="btn btn-primary">Update</button>
</form>
@endsection
然后检查
public function update(Request $request, $id)
{
dd($id);//check id before update
$request->validate([
'title'=>'required',
'body'=>'required'
]);
$post = posts::find($id);
$post->title = $request->get('title');
$post->body = $request->get('body');
$post->save();
return redirect('/');
}