问题描述
我在使用 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 时,它返回给我 Attempt to read property "name" on bool
谁能告诉我我做错了什么?
解决方法
如果您想一次遍历一个属性,请使用 toArray()
$var = model::where('name',$name)->firstOrFail();
$arrayVar = $var->toArray();
foreach( $arrayVar as $name => value) {
//....
}