我正在尝试编辑保存在我的数据库中的数据,但我完全迷失了。
在我的 PostController 中,索引、创建、存储和显示效果很好,但在编辑和更新中我失败了很多。
错误文本
<块引用>未定义变量:id(视图:C:\laragon\www\larablog\resources\views\dashboard\post\edit.blade.php)
PostController.php (app\Http\Controllers\dashboard\PostController.php)
public function edit($id)
{
$post = Post::findOrFail($id);
return view ('dashboard.post.edit', ["post" => $post]);
}
public function update(Request $request, $id)
{
$post = Post::findOrFail($id);
$post::update($request->validated());
return back() -> with('status', '¡Post editado con éxito!');
}
edit.blade.php(资源\视图\仪表板\post\edit.blade.php)
@extends('dashboard.master')
@section('content')
@include('dashboard.partials.validation-error')
<form action="{{ route("post.update", $post->$id) }}" method="PUT">
@csrf
<div class="form-group">
<label for="title">Título</label>
<input class="form-control" type="text" name="title" id="title" value="{{ old('title', $post->title) }}">
@error('title')
<small class="text-danger">
{{ $message }}
</small>
@enderror
</div>
<div class="form-group">
<label for="url_clean">Url limpia</label>
<input class="form-control" type="text" name="url_clean" id="url_clean" value="{{ old('content', $post->url_clean) }}">
</div>
<div class="form-group">
<label for="content">Contenido</label>
<textarea class="form-control" type="text" name="content" id="content" rows="3"> {{ old('content', $post->content) }} </textarea>
</div>
<input type="submit" class="btn btn-primary" value="Enviar">
</form>
@endsection
我不知道为什么会出现这个错误,我需要一点理论来理解这一点。
谢谢大家!
PD我知道如果在 PostController 中,我放了:
<块引用>公共函数编辑(Post $post)
<块引用>公共函数更新($Request $request, Post $post)
我无法避免写:
<块引用>$post = Post::findOrFail($id);
但是我想在 laravel 的第一步中这样写,并且期货 id 不称为“id”
答案 0 :(得分:0)
正如评论指出的,当你从 $post 传递参数时,你必须做这样的事情
<form action="{{ route("post.update", $post->id) }}" method="POST">
@csrf
@method(“PUT”)
因为你没有 id 变量。除此之外,我强烈建议使用路由模型绑定,您可以在其中传递整个模型而不是 id,因为它更清晰,而且您不必在每个方法中都调用 findOrFail。还有更新时使用
$post->update($request->validated());
因为这是调用 update 方法的正确方法,所以当您有 Post 模型而不是变量时使用 ::update。