【问题标题】:Surely noobie Laravel Question: Undefined id? Why? [closed]肯定 noobie Laravel 问题:未定义的 id?为什么? [关闭]
【发布时间】:2021-08-01 16:53:10
【问题描述】:

我正在尝试编辑保存在我的数据库中的数据,但我完全迷路了。

在我的 PostController 中,索引、创建、存储和显示效果很好,但在编辑和更新中我失败了很多。

错误文字

未定义变量:id(查看:C:\laragon\www\larablog\resources\views\dashboard\post\edit.blade.php)

PostController.phpapp\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.phpresources\views\dashboard\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

我不知道为什么会出现这个错误,我需要一点理论来理解这个。

谢谢大家!

P.D.我知道是否在 PostController 中输入:

公共功能编辑(发布$post)

公共函数更新($Request $request, Post $post)

我无法避免写:

$post = Post::findOrFail($id);

但我想在 laravel 的第一步中这样写,而期货 id 不称为“id”

【问题讨论】:

  • id) }}" method="PUT">。它应该是 $post->id 而不是 $post->$id 在表单标签操作 url
  • 表单方法必须是post。告诉 laravel 关于 PUT - 在表单中添加 @method(“PUT”)
  • @JohnLobo 天哪,这就是重点!!!谢啦!把它作为一个答案,我就可以喜欢你和+1!!!!

标签: php laravel laravel-6 laravel-6.2


【解决方案1】:

正如评论指出的,当您从 $post 传递参数时,您必须执行类似的操作

<form action="{{ route("post.update", $post->id) }}" method="POST">
    @csrf
    @method(“PUT”)

因为你没有 id 变量。除此之外,我强烈建议使用路由模型绑定,在其中传递整个模型而不是 id,因为它更简洁,并且您不必在每个方法中都调用 findOrFail。还有更新使用的时候

$post->update($request->validated());

因为这是调用更新方法的正确方法,所以当你有 Post 模型而不是变量时使用 ::update。

【讨论】:

  • $post->更新对我有很大帮助。我遇到的另一个失败是我写了 $post->$id 而不是 $post->id。谢谢大家
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 1970-01-01
  • 1970-01-01
  • 2016-12-03
  • 2019-04-17
  • 2021-11-12
  • 2012-03-16
相关资源
最近更新 更多