How I can check existing property $this->team->playerAssignment->player
in more rational way? Now I check it like this:
if ($this->team)
if (($this->team->playerAssignment))
if (($this->team->playerAssignment->player))
How I can check existing property $this->team->playerAssignment->player
in more rational way? Now I check it like this:
if ($this->team)
if (($this->team->playerAssignment))
if (($this->team->playerAssignment->player))
Try isset php function.
isset — Determine if a variable is set and is not NULL
if(isset($this->team->playerAssignment->player)){
}
The following has always works best for me:
if(isset(Auth::user()->client->id)){
$clientId = Auth::user()->client->id;
}
else{
dump('Nothing there...');
}
The best way is
if (
isset($this->team)
&& isset($this->team->playerAssignment)
&& isset($this->team->playerAssignment->player)
){
// your code here...
}
Because PHP will stops if the first is to false
, if first object exists, it continue to second, and third condition...
Why not use only && $this->team->playerAssignment->player
?! because if player has 0
for value it will be understood as a false
but variable exists !
You can easily check by null coalescing operator
if ($this->team->playerAssignment->player ?? null)
php 8 2024 update here: using the ?-> operator you can do if( $variable?->prop1?->prop2?->prop3 ){ ...
As it's about checking the existence of a property on a certain object, the usage of isset
function could be wrong. isset
function is meant to return a bool value based on the variable or property value is set, and not null, However, it doesn't check for a particular property to exist in the class or instance. Here is the correct way to check the property exists,
$o = new \stdClass();
$o->name = 'Anurag';
var_dump(property_exists($o, 'name')); // true
var_dump(property_exists($o, 'phone')); // false
You can read more details in docs
© 2022 - 2025 — McMap. All rights reserved.
if ($this->team && $this->team->playerAssignment && $this->team->playerAssignment->player)
!! – Brigidabrigit&&
if steps will be more than 3! – Greenbelt