Laravel Arr prepend() function Example

In this example, I will show how to use laravel arr prepend() function. Laravel arr::prepend() function is use to add array element in first position. Also we will show how to insert an item at the beginning of an array in laravel.

If you wish add new array item in first position using arr prepend() method in laravel application.

Read Also :  Laravel Carbon Subtract Minutes Example

Example : Arr::prepend() Method in Laravel

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Arr;

class UserController extends Controller
{
    public function index(){        
        $array1 = ['Desk', 'Table', 'Chair'];

        $prepended1 = Arr::prepend($array1,'Basket');
        print_r($prepended1);
        //['Desk', 'Table', 'Chair','Basket']

        $array2 = ['php', 'laravel', 'html','css'];

        $prepended2 = Arr::prepend($array2,'Vue');
        print_r($prepended1);
        //['php', 'laravel', 'html','css','Vue']
    }
}

Laravel arr prepend() output

['Desk', 'Table', 'Chair','Basket']
['php', 'laravel', 'html','css','Vue']

routes/web.php

<?php

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

Route::get('users', [UserController::class,'index']);

I hope you understand laravel array prepend() function and it can help you…

Read Also :  How Generate PDF From HTML In Laravel dompdf