【问题标题】:i am trying to show single data but it is showing" Trying to get property 'id' of non-object"我正在尝试显示单个数据,但它显示“尝试获取非对象的属性 'id'”
【发布时间】:2021-02-10 05:38:14
【问题描述】:
           **after clicking "read more" i want to show a single post**

               <a href="{{ URL::to('single/blog/'.$post->id) }}" class="btn btn-primary 
                    float-right">Read More &rarr;</a>

             ** **the route is****
               
      Route::get('single/blog/{id}','Web\Site\HomeController@show');

         **the controller is**
          public function show($id)
              {
               $posts = Post::findOrFail($id);
               return view('site.home.singleblog',compact('posts'));
                }

          ****the single section is****
               
  • @foreach($posts 作为 $post) id/image/$post->image") }}" alt=""
{{ $post->name }} {{$post->描述}} @endforeach

【问题讨论】:

    标签: laravel


    【解决方案1】:

    您的变量 $posts 是来自 Post::findOrFail($id) 的单个 Post 实例(其中 $id 来自路由参数,因此是单个值)。您不想迭代模型的实例。在您的视图中使用它,就像单个模型实例而不是集合一样。

    public function show($id)
    {
        view('site.home.singleblog', [
            'post' => Post::findOrFail($id),
        ]);
    }
    

    然后在视图中删除@foreach@endforeach

    【讨论】:

      【解决方案2】:

      试试这个:

      {{ $post['name'] }} {{$post['description']}}
      

      如果您成功获取 $posts,它应该可以工作。错误说 $post 不是对象,但您正在使用对象语法按键获取值。所以使用数组语法。

      【讨论】:

      • 谢谢。但它仍然显示错误“未定义的索引:名称”
      • 正如我在回答中所说,如果您获取 $posts,它应该可以工作。所以在这种情况下,$posts 应该是空的。如果您想获得适当的支持,请正确格式化您的代码。除非我决定花时间,否则您的代码是不可读的。
      猜你喜欢
      • 2019-11-02
      • 1970-01-01
      • 1970-01-01
      • 2021-10-22
      • 2021-09-16
      • 2018-08-08
      • 2019-12-09
      • 1970-01-01
      • 2020-06-02
      相关资源
      最近更新 更多