Laravel Collection Remove Last Item Example

By Hardik Savani November 5, 2023 Category : Laravel

Greetings,

In this post, you will find an illustrative example of how to remove the last element from a Laravel collection. We'll be using Laravel's collection method to remove the final item. I will walk you through a practical example of removing the last item from a Laravel collection. If you have any questions about this process, I'll provide a straightforward example and solution for removing the last item from a Laravel collection.

Laravel collection provide pop() method to remove last item from collection. pop() will remove last element from laravel collection. so, let's see simple example with code.

In Laravel, the pop() method is used to remove and return the last item (element) from a collection. Collections in Laravel are a powerful way to work with arrays of data, and they provide various methods to manipulate and retrieve data from the collection.

Here's how you can use the pop() method in Laravel:

Example:

you can see the below controller code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$collection = collect([

'One',

'Two',

'Three',

'Four'

]);

$collection->pop();

$collection = $collection->toArray();

dd($collection);

}

}

Output:

Array

(

[0] => One

[1] => Two

[2] => Three

)

I hope it can help you...

Shares