Blavitch

In Laravel, getting the last element in a collection is easy if you are familiar with Laravel’s Eloquent.

Collections are a great way to work with arrays of data in Laravel. They provide a fluent, convenient wrapper for working with arrays of data. For example, you may use the collection’s each method to iterate over its items. Collections may also be sorted using the sort method.

When you need to create a chain of methods that map or reduce arrays in Laravel, you’ll love the collection class. It’s located in the Illuminate\Support\Collection location.

The Laravel collection is a valuable feature of the Laravel framework. A collection works like a PHP array, but it is more convenient. A collection allows you to create a chain of methods to map or reduce arrays.

Creating a Collection

You can create your first collection using the following syntax:

$collection = new Collection();

This will return an object named $collection containing two methods: filter and map. The filter method takes no arguments and returns true or false depending on whether the value being filtered is contained within this collection (or not).

The second method, map, takes one argument: the value to be filtered against this list. If both are true then the value will be returned as an array with all its elements present in this list.

Last element

To get the last element of a collection,

collect([2, 6, 7, 12,456,890,1,70,56])->last();
//returns 56

Another example;

collect(['Abijan','Abuja','Lagos','Benin City','Warri','Akure'])->last();
//returns Akure

Happy coding !!!

Leave a Reply

Your email address will not be published. Required fields are marked *