【发布时间】:2020-12-09 12:02:01
【问题描述】:
当我正在学习 laravel 时,我无法理解当我尝试通过在 URL 中键入帖子/编辑来访问我的 edit.blade.php 页面时(该文件位于资源/视图/帖子中) 它正在调用方法 show 并在该页面上打印“show”,如果我输入 posts/posts/edit,edit.blade.php(如下所述)就会出现。请指导我在这里做错了什么
edit.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 create()
{
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('posts/read');
}
public function show($data)
{
echo "show";
}
public function edit($id)
{
return view('posts.edit');
}
public function update(Request $req, $id)
{
echo posts::where('title' , $req->title)
->update(['body'=>$req->body]);
return redirect('/');
}
public function destroy($id)
{
$post = posts::find($id);
$post->delete();
return redirect('/');
}
}
路线:
Route::resource('posts', 'PostController');
【问题讨论】:
-
您遇到了哪个错误?在此处查看官方资源控制器文档laravel.com/docs/7.x/controllers#resource-controllers
-
您不使用模型路由绑定,这可能会解决您的问题。不要将
$id发送到您的控制器(每个方法的参数),只需执行posts $post。然后你就准备好了$post变量,你不需要手动获取它。 -
另外,旁注 - 你的模型违反了 Laravel 命名约定。它应该是
Post(第一个字母大写,单数)而不是posts(全小写,复数)。 -
如果你刚开始使用这个模型和那个控制器,你最好删除它们,然后用
php artisan make:model Post -rc重新生成它们(生成模型Post,并使用已经定义的资源丰富的控制器)。
标签: php laravel eloquent laravel-7