Laravel check property exist
Asked Answered
P

6

8

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))
Poucher answered 19/9, 2017 at 13:21 Comment(5)
what about if ($this->team && $this->team->playerAssignment && $this->team->playerAssignment->player) !!Brigidabrigit
I think it is the same. And what if steps will be more than 3?Poucher
You can check it using other && if steps will be more than 3!Greenbelt
Did you try if(isset($this->team->playerAssignment->player)) ?Acaulescent
I tried it in laravel blades. And it worked. But in controllers isset($this->team->playerAssignment->player) always return false(Poucher
D
21

Try isset php function.

isset — Determine if a variable is set and is not NULL


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

}
Duane answered 19/9, 2017 at 13:42 Comment(0)
F
2

The following has always works best for me:

if(isset(Auth::user()->client->id)){
        $clientId = Auth::user()->client->id;
    }
    else{
        dump('Nothing there...');
    }
Fidole answered 14/8, 2020 at 10:58 Comment(0)
L
1

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 !

Lean answered 19/9, 2017 at 13:52 Comment(0)
O
0

You can easily check by null coalescing operator

if ($this->team->playerAssignment->player ?? null)
Ordovician answered 10/10, 2020 at 19:40 Comment(1)
Needs details or clarityHaw
C
0

php 8 2024 update here: using the ?-> operator you can do if( $variable?->prop1?->prop2?->prop3 ){ ...

Campuzano answered 22/2, 2024 at 22:57 Comment(0)
K
0

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

Kimmy answered 29/6, 2024 at 5:32 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.