Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I safely retrieve this property of this object?

I have a Stripe subscription object that looks like this...

subscription: {
    items: {
        data: [
            plan: {
                id: 'my_plan_id'
            }
        ]
    }
}

What's the best way to safely retrieve the plan id? Currently I am doing the following.

'plan_id' => $subscription->items->data[0]->plan->id,

But, it looks like that will fail if items, data[0], or plan, is not set. I could do nest if statements like, if (isset($subscription->items) && isset(data[0]) ..., but I am not sure that is the best way.

Is there a PHP method or Laravel method that I can use to extract that property safely that would be cleaner than that?

like image 222
Henry Avatar asked Jun 30 '17 13:06

Henry


3 Answers

If you're using PHP 7+, you can use the null coalesce operator:

'plan_id' => $subscription->items->data[0]->plan->id ?? $default,

This will evaluate the value if it's available, otherwise it will use the default, without generating any warnings or errors.

Example:

$foo = new stdClass();
var_dump($foo->bar->baz->data[0]->plan->id ?? null);

Output:

NULL
like image 116
Alex Howansky Avatar answered Oct 02 '22 14:10

Alex Howansky


You can use an isset function over the entire selector:

isset($subscription->items->data[0]->plan->id) ? $subscription->items->data[0]->plan->id : null;
like image 32
Jerodev Avatar answered Oct 02 '22 14:10

Jerodev


in PHP version 8

you should use Nullsafe operator as follow:

'plan_id' => $subscription?->items?->data[0]?->plan->id,
like image 28
Ali_Hr Avatar answered Oct 02 '22 13:10

Ali_Hr