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?
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
You can use an isset
function over the entire selector:
isset($subscription->items->data[0]->plan->id) ? $subscription->items->data[0]->plan->id : null;
in PHP version 8
you should use Nullsafe operator as follow:
'plan_id' => $subscription?->items?->data[0]?->plan->id,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With