Using Arr::get() in Laravel 11.x & Laravel 12.x

In Laravel 11.x & Laravel 12.x, the `Arr::get()` method is part of the `Illuminate\Support\Arr` class and is used to retrieve a value from a deeply nested array or object using “dot notation”. This is particularly useful when you want to safely access a value without worrying about undefined keys or nested levels.

How to Use `Arr::get()`

Syntax:

<?php
Arr::get(array|object $array, string $key, mixed $default = null);
?>

-> `$array`: The array or object from which to retrieve the value.
->`$key`: The key in “dot notation” to access the value.
->`$default`: (Optional) The default value to return if the key does not exist.

1. Basic Usage

use Illuminate\Support\Arr;
$array = [
'user' => [
'name' => 'John Doe',
'email' => 'john@example.com',
],
];

// Retrieve the user's name
$name = Arr::get($array, 'user.name'); // 'John Doe'

// Retrieve a non-existent key with a default value
$age = Arr::get($array, 'user.age', 30); // 30

2. Using Dot Notation for Nested Arrays

$array = [
'settings' => [
'theme' => [
'color' => 'blue',
'font' => 'Arial',
],
],
];

// Retrieve the theme color
$color = Arr::get($array, 'settings.theme.color'); // 'blue'

// Retrieve a non-existent key with a default value
$size = Arr::get($array, 'settings.theme.size', 'medium'); // 'medium'

3. Using `Arr::get()` with Objects

`Arr::get()` also works with objects that implement the `ArrayAccess` interface (e.g., Eloquent models).

$user = (object) [
'profile' => (object) [
'username' => 'johndoe',
],
];

// Retrieve the username
$username = Arr::get($user, 'profile.username'); // 'johndoe'

Conclusion

`Arr::get()` is a powerful utility in Laravel for safely accessing nested array or object values. It simplifies your code and avoids the need for repetitive `isset()` checks. Use it whenever you’re working with deeply nested data structures.