How to get nested key values in laravel?

Member

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

How to get nested key values in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 9 months 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' => 'johndoe@example.com',
    ]
];


You can access the nested key values like this:

1
2
$name = $data['user']['name']; // John Doe
$email = $data['user']['email']; // johndoe@example.com


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'); // johndoe@example.com


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'); // johndoe@example.com


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

Related Threads:

How to get distinct values from nested table in oracle?
How to get the value of foreign key in laravel?
How to get values of checkbox array in laravel?
How to select / get values from database in laravel?
How to get values from pivot table in laravel?
How to get object values inside array in laravel?