How to get nested key values in laravel?

Member

by larissa , in category: PHP Frameworks , 9 days ago

How to get nested key values in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 8 days ago

@larissa 

In Laravel, you can access nested key values in an array using dot notation. For example, if you have an array like this:

1
2
3
4
5
6
$data = [
    'user' => [
        'name' => 'John Doe',
        'email' => '[email protected]',
    ]
];


You can access the nested key values like this:

1
2
$name = $data['user']['name']; // John Doe
$email = $data['user']['email']; // [email protected]


If you want to access nested key values from a Laravel collection, you can use the get method with dot notation:

1
2
3
4
$user = collect($data);

$name = $user->get('user.name'); // John Doe
$email = $user->get('user.email'); // [email protected]


Alternatively, you can use the Arr helper class to access nested key values in an array:

1
2
3
4
use IlluminateSupportArr;

$name = Arr::get($data, 'user.name'); // John Doe
$email = Arr::get($data, 'user.email'); // [email protected]


By using dot notation and Laravel's helper methods, you can easily access nested key values in Laravel arrays and collections.