How to Add Items at the Beginning to a Collection in Laravel?

Nov 15, 2022 . Admin



Hello Friends,

In this tutorial, you will learn how to add items at the beginning of a collection in laravel. we will help you to give examples of how to add values to a collection at the beginning in laravel. I would like to show you laravel add elements at the beginning of a collection. let’s discuss the laravel collection add items at the beginning example. Alright, let’s dive into the steps.

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\AddAtBeginningController;

/*
|--------------------------------------------------------------------------
| 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',[AddAtBeginningController::class, 'index']);
Step 3: create AddAtBeginningController

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

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

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AddAtBeginningController extends Controller
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
    */
    public function index()
    {
        // Create a new collection instance.
        $collection = new Collection(['a' => 'Doe', 'b' => "John" , 'c' => "Gadas" , 'd' => "Maxy"]);
         
        // Add a new item to the beginning of the collection.
        $collection->prepend('Rowan', 'e');
        
        dd($collection);
    }
}
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:
#items: array:5 [▼
    "e" => "Rowan"
    "a" => "Doe"
    "b" => "John"
    "c" => "Gadas"
    "d" => "Maxy"
]

I hope it can help you...

#Laravel