Laravel 检查属性是否存在

问题描述 投票:0回答:5

如何更合理地查询现有房产

$this->team->playerAssignment->player
?现在我这样检查:

if ($this->team)
   if (($this->team->playerAssignment))
      if (($this->team->playerAssignment->player))
laravel properties exists
5个回答
19
投票

尝试 isset php 函数。

isset — 确定变量是否已设置且不为 NULL


if(isset($this->team->playerAssignment->player)){

}

2
投票

以下内容始终最适合我:

if(isset(Auth::user()->client->id)){
        $clientId = Auth::user()->client->id;
    }
    else{
        dump('Nothing there...');
    }

1
投票

最好的方法是

if (
    isset($this->team)
    && isset($this->team->playerAssignment)
    && isset($this->team->playerAssignment->player)
){
    // your code here...
}

因为如果第一个条件是

false
,PHP 将停止,如果第一个对象存在,它将继续第二个和第三个条件... 为什么不只使用
&& $this->team->playerAssignment->player
?!因为如果玩家有
0
的值,它将被理解为
false
但变量存在!


0
投票

您可以通过空合并运算符轻松检查

if ($this->team->playerAssignment->player ?? null)

0
投票

php 8 2024 更新在这里:使用 ?-> 运算符你可以这样做 if( $variable?->prop1?->prop2?->prop3 ){ ...

© www.soinside.com 2019 - 2024. All rights reserved.