Laravel Collection Remove Last Item Example
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
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Get Random Item from Laravel Collection?
- How to Convert Collection to Array in Laravel?
- Laravel Convert Collection to Array Example
- Top Recommendations for College Homework
- Laravel Collection Get Unique Values Example
- Laravel Collection Get First and Last Item Example
- Laravel Collection Check Contains Value Example
- Laravel Collection Has Method Example
- Laravel Collection Except() Method Example
- Laravel Collection Duplicates Method Example
- Laravel Collection diff(), diffAssoc() and diffKeys() Example
- Laravel Collection Unique | Remove Duplicates from Collection Laravel
- Laravel Collection Filter Method Example