How can I safely retrieve this property of this object?

Viewed 3440

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?

5 Answers

in PHP version 8

you should use Nullsafe operator as follow:

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