试图在laravel中获取非对象的属性

斯科特

我有以下代码

在控制器中

  public function ViewPost($id)
        {
             $viewpost= Post::find($id);
              return view('Guest.viewpost', ['viewpost'=>$viewpost]);
        }

视线中

  @foreach($viewpost as $val)

        <br>
        Post title=
        <a href="viewpost/{{$val->id}}" >{{$val->post_title}}</a>
      <br>
        Post content={{$val->post_content}}
        <br>  <br>
        Featured Image=<img src="{{$val->featured_image}}" height="150" width="150">
      @endforeach

但是上面的代码抛出错误,Trying to get property of non-object.所以我尝试了以下方法

 $val['post_title'];

上面的代码不会引发错误,也不会显示输出。

如果我在控制器中打印,则显示输出,但在视图中显示相同,如果给出错误

 print_r($viewpost);

我正在使用laravel 5.1.有人可以告诉我们我做错了吗?
谢谢你。

更新

在@ CodeRomeos.i的建议后,可以显示未加载的数据图像。

<img src="{{$val->featured_image}}" height="150" width="150">

<img src="uploads/penguin.jpg">

展览视图中的相同作品

CodeRomeos

像这样更新您的控制器

public function ViewPost($id)
{
     $viewpost= Post::find($id)->first();
      return view('Guest.viewpost', ['viewpost'=>$viewpost]);
}

或者

public function ViewPost($id)
{
     $viewpost= Post::find($id)->get();
      return view('Guest.viewpost', ['viewpost'=>$viewpost]);
}

如果仍然遇到问题,请回来。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章