ItSolutionStuff.com

Laravel Collection Push() and Put() Example

By Hardik Savani • April 16, 2024
Laravel

Hi,

This article goes in detailed on laravel collection push and pull example. i would like to show you laravel collection put example. it's simple example of laravel collection put array. i explained simply step by step laravel collection push key value. Here, Creating a basic example of laravel collection add key value.

I will give you some examples of how to adding key value pair array to collection in laravel. you can easily add array in laravel 5, laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11.

Let's see example:

Example 1: Laravel Collection Push Example

public function index()

{

$collection = collect(['one', 'two', 'three']);

$collection->push('four');

$collection->all();

dd($collection);

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => one

[1] => two

[2] => three

[3] => four

)

)

Example 2: Laravel Collection Push with Array Example

public function index()

{

$collection = collect([

['id'=>1, 'name'=>'Hardik'],

['id'=>2, 'name'=>'Harsukh'],

['id'=>3, 'name'=>'Bhagat'],

]);

$collection->push(['id'=>4, 'name'=>'vimal']);

$collection->all();

dd($collection);

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[0] => Array

(

[id] => 1

[name] => Hardik

)

[1] => Array

(

[id] => 2

[name] => Harsukh

)

[2] => Array

(

[id] => 3

[name] => Bhagat

)

[3] => Array

(

[id] => 4

[name] => vimal

)

)

)

Example 3: Laravel Collection Add with Key Value Pair

public function index()

{

$collection = collect(['id' => 1, 'name' => 'Hardik']);

$collection->put('role', 'admin');

$collection->all();

dd($collection);

}

Output:

Illuminate\Support\Collection Object

(

[items:protected] => Array

(

[id] => 1

[name] => Hardik

[role] => admin

)

)

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Collection SortBy Tutorial with Examples

Read Now →

Laravel Collection Merge | How to Merge Two Eloquent Collection?

Read Now →

Laravel Collection Unique | Remove Duplicates from Collection Laravel

Read Now →

Laravel Collection Search Method Example

Read Now →

Laravel Collection Filter Method Example

Read Now →

Laravel 8/7 Paginate with Collection or Array

Read Now →

Merge Multiple Collection Paginate in Laravel

Read Now →