【问题标题】:Attempt to read property "name" on bool尝试在 bool 上读取属性“名称”
【发布时间】: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


【解决方案1】:

如果您想一次遍历一个属性,请使用toArray()

$var  =  model::where('name', $name)->firstOrFail();
$arrayVar = $var->toArray();

foreach( $arrayVar as $name => value) {
    //....
}

【讨论】:

    猜你喜欢
    • 2021-05-02
    • 1970-01-01
    • 2021-05-17
    • 2021-05-25
    • 2021-12-07
    • 1970-01-01
    • 2021-08-08
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多