【问题标题】:How to allow user to edit posts? I am using laravel 8如何允许用户编辑帖子?我正在使用 laravel 8
【发布时间】:2021-06-11 12:08:11
【问题描述】:

我正在尝试允许用户编辑帖子,但是我不断收到此错误:

Property [caption] does not exist on this collection instance. (View: C:\xampp\htdocs\myprojectname\resources\views\posts\edit-post.blade.php)

我在 Post Controller 中的编辑功能是:

use App\Models\Post;
     
public function edit(Post $post)
      {
    
        return view('posts.edit-post', ['post' => $post]);

      }

我在 Post Controller 中的更新功能是:

public function update(Post $post, Request $request)
  {

    $data = request()->validate([
      'caption' => 'nullable',
      'url' => 'nullable',
      'image' => 'nullable',
    ]);

    $updateData = [
     'caption' => $data['caption'],
     'url' => $data['url'],
   ];

   if (request('image')) {
     $imagePath = request('image')->store('uploads', 'public');
     $updateData['image'] = $imagePath;
   }

   auth()->user()->posts()->id()->update($updateData);

   return redirect('/users/' . auth()->user()->id);

  }

我的edit-post.blade.php文件代码是:

@section('content')
<body class="create_body">
  <div class="create_container_div">

    <form action="{{('/users/' . auth()->user()->id)}}" enctype="multipart/form-data" method="post">
      @csrf
      @method('PATCH')

      <div class="form-group">
          <label for="caption" class="create_caption_label">Post Caption</label>

          <div class="create_caption_div">
              <input id="caption"
              type="text"
              class="form-control @error('caption') is-invalid @enderror"
              name="caption"
              value="{{ old('caption') ?? auth()->user()->posts->caption }}"
              autocomplete="caption" autofocus>

              @error('caption')
              <div class="invalid-feedback-div">
                <span class="invalid-feedback" role="alert">
                    <strong>{{ $message }}</strong>
                </span>
              </div>
              @enderror
          </div>
      </div>

      <div class="form-group">
          <label for="url" class="edit_title_label">URL</label>

          <div class="edit_url_div">
              <input id="url"
              type="text"
              class="form-control @error('url') is-invalid @enderror"
              name="url"
              value="{{ old('url') ?? auth()->user()->posts->url }}"
              autocomplete="url" autofocus>

              @error('url')
              <div class="invalid-feedback-div">
                <span class="invalid-feedback" role="alert">
                    <strong>{{ $message }}</strong>
                </span>
              </div>
              @enderror
          </div>
      </div>

      <div class="create_post_image_div">
        <label for="image" class="create_image_label">Post Image</label>
        <input type="file" class="form-control-file" id="image" name="image">

        @error('image')
        <div class="invalid-feedback-div">
          <strong>{{ $message }}</strong>
        </div>
        @enderror

        <div class="create_post_btn_div">
          <button class="create_post_btn">Save Changes</button>
        </div>
      </div>

    </form>

  </div>
</body>
@endsection

我的 create_posts_table 迁移文件是:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->string('caption');
            $table->string('url');
            $table->string('image');
            $table->timestamps();

            $table->index('user_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

而我的 Post.php 模型文件是:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function user()
    {
      return $this->belongsTo(User::class);
    }

}

最后我在 web.php 中的路由是:

use App\Http\Controllers\PostsController;

Route::get('/posts/{post}/edit', [PostsController::class, 'edit']);

Route::patch('/posts/{post}', [PostsController::class, 'update'])->name('posts.update');

如何解决此问题,以及如何允许用户编辑帖子?

【问题讨论】:

  • Post::where('id')-&gt;first(); ... where('id') 什么?缺少一个参数。而且,你已经通过方法参数得到$post
  • use App\Http\Controllers\PostsController 缺少;,应该抛出错误
  • " 使用 App\Http\Controllers\PostsController 缺少一个 ;" 抱歉,我复制并粘贴了错误,省略了 ' ; ' 当我真的已经在文件中正确输入它时。
  • " Post::where('id')->first(); ... where('id') 什么?缺少参数。而且,您已经通过方法参数获得了 $post ” 。我想了很多,尽管我试图提出错误即将出现的建议,因为我必须遍历一系列帖子来获取要编辑的帖子的 id。因此,此集合实例上不存在 Property [caption] 的错误。现在我不确定该尝试什么...

标签: php laravel model-view-controller eloquent laravel-8


【解决方案1】:

这行不正确,我不知道你是不是来自其他语言,这对我来说完全没有意义。

auth()->user()->posts()->id()->update($updateData);

Post 已经在您所在的上下文中,因为它在您的控制器方法 public function update(Post $post, Request $request) 中绑定了模型,您可以使用它来更新它。 fill()$updateData 应用于模型,save() 将其写入数据库。

$post->fill($updateData);
$post->save();

正如 cmets 所说,edit 函数缺少一个 id,同样您已经将模型绑定到该方法,然后使用它。

public function edit(Post $post)
{
    return view('posts.edit-post', ['post' => $post]);
}

【讨论】:

  • 这是我之前的代码,但出现了同样的错误。
  • " Post::where('id')->first(); ... where('id') 什么?缺少参数。而且,您已经通过方法参数获得了 $post ” 。我想了很多,尽管我试图提出错误即将出现的建议,因为我必须遍历一系列帖子来获取要编辑的帖子的 id。因此,此集合实例上不存在 Property [caption] 的错误。现在我不确定该尝试什么...
  • "此行不正确,我不知道您是否来自其他语言,这对我来说完全没有意义:auth()->user()->posts( )->id()->update($updateData); " 这一行在类似的用例中工作,它帮助用户编辑个人资料详细信息,而不必在表单中再次重新提交相同的个人资料图像。我想对帖子使用相同的逻辑,除了我认为我可能必须指定获取帖子 ID 来解决错误。因此,我在该行代码中包含了 id()。
  • 在这两种情况下,您都有来自模型绑定的 Post,所以只需使用 $post 而不是获取它或使用关系来获取它?
  • 如我的回答中所述,不要进行您正在做的关系更新,只需像新问题中的人所说的那样更新 $post 即可。如果这有助于您解决问题,请接受作为答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2016-01-02
  • 1970-01-01
  • 1970-01-01
  • 2015-05-28
相关资源
最近更新 更多