How to Add Multiple Items to a Collection in Laravel?

Nov 11, 2022

.

Admin

How to Add Multiple Items to a Collection in Laravel?

Hello Friends,

In this tutorial, I will show you how to add multiple items to a collection in laravel. we will help you by giving an example of a laravel collection adding multiple items. We will use add multiple elements to the laravel collection. you will learn how to add multiple values to a collection in laravel. follow the below step for the laravel collection and adds multiple item examples.

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