How to create nested collections in laravel?

by filiberto , in category: PHP Frameworks , 6 months ago

How to create nested collections in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by shyann , 6 months ago

@filiberto 

To create nested collections in Laravel, you can make use of the 'collect' helper function provided by Laravel. The collect function creates a new collection instance.


Here is an example of how you can create a nested collection:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
use IlluminateSupportCollection;

$collection = collect([
    [
        'name' => 'John Doe',
        'email' => '[email protected]',
        'orders' => [
            [
                'product' => 'Laptop',
                'price' => 1000,
            ],
            [
                'product' => 'Phone',
                'price' => 500,
            ],
        ]
    ],
    [
        'name' => 'Jane Doe',
        'email' => '[email protected]',
        'orders' => [
            [
                'product' => 'Tablet',
                'price' => 800,
            ],
        ]
    ],
]);


In this example, we have created a collection with two nested arrays, each containing information about a user and their orders. The user's information includes their name and email, and their orders are stored in another nested array.


You can access the nested collections using the dot notation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Accessing user's name
$name = $collection[0]['name'];

// Accessing user's first order's product
$product = $collection[0]['orders'][0]['product'];

// Looping through the collection
foreach ($collection as $user) {
    // Accessing user's name
    $name = $user['name'];
    
    // Looping through user's orders
    foreach ($user['orders'] as $order) {
        // Accessing order's product and price
        $product = $order['product'];
        $price = $order['price'];
    }
}


You can also make use of the collection methods provided by Laravel to perform various operations on the nested collection, such as filtering, mapping, sorting, etc.