【发布时间】:2021-05-26 17:33:14
【问题描述】:
我在使用 Laravel 8 时遇到问题,不知道如何识别错误。
会发生以下情况..
在我的控制器中是这样的:
$var = model::where('name', $name)->firstOrFail();
print_r($var)
Print_r 在这里返回给我
App\Models\test Object (
[table:protected] => tb_test
[timestamps] =>
[connection:protected] => mysql
[primaryKey:protected] => id
[keyType:protected] => int
[incrementing] => 1
[with:protected] => Array ( )
[withCount:protected] => Array ( )
[perPage:protected] => 15
[exists] => 1
[wasRecentlyCreated] =>
[attributes:protected] => Array (
[id] => 48494980
[name] => TEST
)
[original:protected] => Array (
[id] => 48494980
[name] => TEST
)
[changes:protected] => Array ( )
[casts:protected] => Array ( )
[classCastCache:protected] => Array ( )
[dates:protected] => Array ( )
[dateFormat:protected] =>
[appends:protected] => Array ( )
[dispatchesEvents:protected] => Array ( )
[observables:protected] => Array ( )
[relations:protected] => Array ( )
[touches:protected] => Array ( )
[hidden:protected] => Array ( )
[visible:protected] => Array ( )
[fillable:protected] => Array ( )
[guarded:protected] => Array ( [0] => * )
)
当我尝试使用 foreach 时,它返回我 尝试在 bool 上读取属性“名称”
谁能告诉我我做错了什么?
【问题讨论】:
-
你是如何使用 foreach 的?
$var是单个模型,而不是集合,因此不需要 foreach -
你试过使用getter吗?
-
要在 laravel 中调试结果,你应该使用
dd()而不是print_r()或var_dump(),除非你对自己正在做的事情有信心。无论如何, $var 包含一个对象实例,你不能在它上面进行 foreach 。如果要遍历属性,请使用toArray() -
使用 toArray() 工作感谢您的时间,伙计们
标签: php laravel foreach eloquent laravel-8