访问控制器内部的编辑功能

问题描述 投票:0回答:4

您好,laravel的朋友来了。我正在尝试编辑我的帖子,当我尝试访问控制器中的edit功能时,我得到了此error Property [id] does not exist on this collection instance.

这是我的路线代码

Route::resource('/article','PostController'); 

这是我的控制人

public function edit(Post $post)
{

    $post = Post::all();
    return view('article.edit',compact('post'));

}

这是我的查看代码

<a href="{{route('article.edit', $post->id)}}" class="btn btn-info btn-sm btn-bordred wave-light"> 
<i class="fas fa-edit"></i></a>

解决方法?在此先感谢

laravel
4个回答
1
投票

当您使用“全部”时,您将从帖子表中获取所有数据。在编辑功能中,您将获得$ id作为参数。

public function edit($id)
{

    $post = Post::find($id);
    return view('article.edit',compact('post'));

}

1
投票

您正在将collection传递到view,而不是单个帖子

public function edit(Post $post)
{

    $post = Post::all(); // this is a collection of posts
    return view('article.edit',compact('post'));

}

应该是:

public function edit(Post $post)
{
    // here $post holds the instance of single/current post

    return view('article.edit',compact('post'));

}

然后输入blade

<a href="{{route('article.edit', ['post' => $post->id ])}}" class="btn btn-info btn-sm btn-bordred wave-light"> 
<i class="fas fa-edit"></i></a>

注意:由于您将$post作为模型的instance进行传递,因此您不必使用Post::find(); laravel将在后端自动处理此问题

谢谢


0
投票

[Post::all()返回一个集合(多个模型)

您需要在edit($id) function中传递ID,然后才能find($id)

 public function edit($id){
      $post = Post::find($id);
      return view('article.edit')->with('post', $post);
 }

0
投票

这是因为变量$post拥有Laravel集合。您必须迭代该集合才能访问每个帖子模型。

// Returns a collection of posts model (think of 
// it as an array of posts)
$post = Post::all();

在刀片上,使用foreach遍历每个帖子。

编辑

[我看到您已经有一个帖子实例,在这种情况下,只需使用此代码

public function edit(Post $post)
{
    return view('article.edit', ["post" =>$post]);
}
© www.soinside.com 2019 - 2024. All rights reserved.