Simplify Complex Array Access in Laravel with data_get()
Laravel’s data_get() helper makes working with complex and nested data structures effortless. This article shows practical patterns to extract values cleanly using dot notation and wildcards—without repetitive checks.
Example 1: Extracting Values from Variant-Based Data
$products = [
'desk' => [
['sku' => 'D-1', 'stock' => 10],
['sku' => 'D-2', 'stock' => 0],
],
'chair' => [
['sku' => 'C-1', 'stock' => 5],
],
];
$stocks = data_get($products, 'desk.*.stock');
Result:
[10, 0]
✔ Clean
✔ No loops
✔ No conditions
Example 2: Reading a Specific Position in a Sequence
$journey = [
'stops' => [
['city' => 'Delhi', 'time' => '08:00'],
['city' => 'Dubai', 'time' => '13:30'],
['city' => 'London', 'time' => '18:45'],
],
];
$finalStop = data_get($journey, 'stops.2.city');
You get exactly what you want, without checking array indexes manually.
Example 3: Mixing Wildcards with Defaults
$orders = [
['id' => 1, 'total' => 250],
['id' => 2],
['id' => 3, 'total' => 400],
];
$totals = data_get($orders, '*.total', 0);
Result:
[250, 0, 400]
This is extremely useful when working with partially filled API responses.