laravel - 试图为 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);
解决方案
我想你几乎在那里。尝试使用first()
而不是get()
.
DB::table('users')
->select('*')
->where('id', '=', 5)
->first();
这应该返回一个实例StdClass
而不是一个集合。
如果您仍然收到相同的错误,则可能是没有匹配 ID 5 的记录。
推荐阅读
- excel - 我在代码上收到“错误 9:下标超出范围”
- javascript - 在 AntD 分拣机上需要键盘可访问性(tab+enter)
- git - SSHing github 耗时太长
- regex - 匹配以 '/' 开头的字符的所有实例
- jmeter - 在Jmeter中将两个字符串变量合二为一
- javascript - 日历错误未定义变量中的PHP颜色
- linux - fio中的顺序读写是什么意思?
- java - 休息端点使用java在aws cognito中注册用户?
- c++ - Lares - 他们将 c 人分成 t 组
- python - Pandas read_excel 函数错误地从 excel 文件中读取数据