Laravel Collection Add Multiple Item Example

Nov 11, 2022 . Admin



Hello Friends,

This tutorial is focused on the laravel collection and adding multiple item examples. you will learn how to add multiple items to a collection in laravel. if you have a question about laravel adding multiple items to a collection then I will give a simple example with a solution. you can see add multiple elements in the laravel collection. So, let's follow a few steps to create an example of how to add multiple values to a collection in laravel.

You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.

You have just to follow the below step and you will get the layout as below:

Step 1: Install Laravel

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app
Step 2: Create Format Route web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AddMultipleItemController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/index',[AddMultipleItemController::class, 'index']);
Step 3: create AddMultipleItemController

we will create AddMultipleItemController. so you can see the below code with output:

php artisan make:controller AddMultipleItemController
App\Http\Controllers\AddMultipleItemController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AddMultipleItemController extends Controller
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
    */
    public function index()
    {
        $collection = collect(['a' => 'Doe', 'b' => "John" , 'c' => "Gadas" , 'd' => "Maxy"]);

        $requiredList = [];

        foreach($collection as $key => $value){
            $requiredList[] = (object)[
                'customer_id' => $key,
                'name' => $value
            ];
        }
        
        dd($requiredList);
    }
}
Step 4: Start Development Server

Start the development server. Use the PHP artisan serve command and start your server:

php artisan serve

Now you are ready to run our example so run the below command to quick run.

http://localhost:8000/index
Output:
array:4 [▼ // app/Http/Controllers/AddMultipleItemController.php:27
    0 => {#1219 ▼
        +"customer_id": "a"
        +"name": "Doe"
    }
    1 => {#1220 ▼
        +"customer_id": "b"
        +"name": "John"
    }
    2 => {#1221 ▼
        +"customer_id": "c"
        +"name": "Gadas"
    }
    3 => {#1222 ▼
        +"customer_id": "d"
        +"name": "Maxy"
    }
]

I hope it can help you...

#Laravel