Skip to main content
Quick Tip

Dealing with deeply-nested arrays

If you have a complex array, you can use data_get() helper function to retrieve a value from a nested array using "dot" notation and wildcard.

$data = [
0 => ['user_id' => 1, 'created_at' => 'timestamp', 'product' => {object Product}],
1 => ['user_id' => 2, 'created_at' => 'timestamp', 'product' => {object Product}],
2 => etc
];
 
// Now we want to get all products ids. We can do like this:
 
data_get($data, '*.product.id');
 
// Now we have all products ids [1, 2, 3, 4, 5, etc...]

In the example below, if either request, user or name are missing then you'll get errors.

$value = $payload['request']['user']['name'];
 
// The data_get function accepts a default value, which will be returned if the specified key is not found.
 
$value = data_get($payload, 'request.user.name', 'John')

Tip given by @mattkingshott

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.