How to Remove the Last Element From Collection in Laravel?

Oct 21, 2022 . Admin

Hello Friends,

Now, let's see a tutorial on how to remove the last element from a collection in laravel. This tutorial will give you a simple example of laravel removing the last item in a collection. I explained simply step by step how to remove the last element from a collection in laravel. I would like to show you that laravel remove the last item from the collection. Follow the below tutorial step of the laravel collection the last item was removed.

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

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

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

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

php artisan make:controller RemoveLastController

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class RemoveLastController extends Controller
     * The attributes that are mass assignable.
     * @var array
    public function index()
        $myCollection = collect(['a','b','c','d','e']);

        $myCollection = $myCollection->reverse()->slice(1)->reverse();
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.

#items: array:4 [▼
    0 => "a"
    1 => "b"
    2 => "c"
    3 => "d"

i hope it can help you...