首页 > 解决方案 > 试图为 laravel 控制器上的一个列表获取非对象的属性?

问题描述

我只从我的数据库中获得一份清单

        $postalls=
        DB::table(users)
        ->select('*')
        ->where('id','=',5)
        ->get();

return View('codo.postview')
                ->with('postalls', $postalls); 

当我在 postview.blade.php 上使用下面时

{{$postalls[0]->comment}}

我收到错误消息

Trying to get property of non-object

我知道我可以通过使用来解决视图问题

 @foreach($postalls as $postall)
   {{$postall->comment}}
 @endforeach

不过我想问~

我可以不使用 foreach 函数来修复错误消息吗?

我也在下面尝试,但我得到了同样的错误我可以将集合转移到对象吗?

  $postalls=
    DB::table(users)
    ->select('*')
    ->where('id','=',5)
    ->get()
    ->first();

{{$postalls->title}}

使用 first() 或不使用 get() dd($postalls) 得到相同的结果~ 在此处输入图像描述

我的 id 来自按下并发送到控制器的按钮

   public function postshow($table,$id)
    {

        $postallsold=
        DB::table($table)
        ->select('*')
        ->where('id','=',$id)
        ->get()
        ->first();
      dd($postallsold);

在此处输入图像描述

标签: laravelobjectcollectionslaravel-query-builder

解决方案


我想你几乎在那里。尝试使用first() 不是get().

DB::table('users')
->select('*')
->where('id', '=', 5)
->first();

这应该返回一个实例StdClass而不是一个集合。

如果您仍然收到相同的错误,则可能是没有匹配 ID 5 的记录。


推荐阅读