In Laravel, you can use the
pop()
method to remove the last item from a collection. Here’s an example:
use Illuminate\Support\Collection;
// Create a sample collection
$collection = new Collection([1, 2, 3, 4, 5]);
// Remove the last item from the collection
$removedItem = $collection->pop();
// Output the updated collection and the removed item
dd($collection, $removedItem);
In this example, the pop()
method is called on the collection, and it removes the last item (5 in this case). The dd()
function is used to dump and die, which means it will output the updated collection and the removed item, and then terminate the script.
After running this code, you’ll see that the last item has been removed from the collection, and the output will look like this:
Illuminate\Support\Collection {#1
all: [ 1, 2, 3, 4, ],
}
5
Now, the collection contains only the first four elements, and the removed item is the last element (5).