ItSolutionStuff.com

Laravel Collection Remove Last Item Example

By Hardik Savani • November 5, 2023
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...

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

How to Get Random Item from Laravel Collection?

Read Now →

How to Convert Collection to Array in Laravel?

Read Now →

Laravel Convert Collection to Array Example

Read Now →

Top Recommendations for College Homework

Read Now →

Laravel Collection Get Unique Values Example

Read Now →

Laravel Collection Get First and Last Item Example

Read Now →

Laravel Collection Check Contains Value Example

Read Now →

Laravel Collection Has Method Example

Read Now →

Laravel Collection Except() Method Example

Read Now →

Laravel Collection Duplicates Method Example

Read Now →

Laravel Collection diff(), diffAssoc() and diffKeys() Example

Read Now →

Laravel Collection Unique | Remove Duplicates from Collection Laravel

Read Now →

Laravel Collection Filter Method Example

Read Now →