last(), this is the opposition method of the first() method and this method will be used to find the last item from the collection. or it will get the last item in a collection that matched certain criteria $callback can be supply collection that matched a given true of the collection.
So in this post, you will learn the different various ways to collect the last item from the collection with the example.
Example 1
This is a simple example of last value of the collection will return from the collection using last() method.
return collect([1,2,3,4])->last(); // OUTPUT // 4
Example 2
In this example, we used the callback method to return based on the condition base return last value from the collection.
return collect([1,2,3,4])->last(function($element){ return $element < 3; // return true or false }); // OUTPUT // 2
Example 3
In this example if the collection will have an empty array or if you want to return a default value from this collection you required two arguments to pass first is NULL and the second is what value you want to return as the default value.
return collect([])->last(null,166); // default value // OUTPUT // 166
Example 4
This there is no empty array you can also define the same argument pass in the last() method.
return collect()->last(null,166); // OUTPUT // 166
Example 5
You can also use the default value with callback, if the inside the callback condition returns false always then it will take at least the default value from this collection.
return collect([1,2,3,4])->last(function($element){ return $element < 4; },111); // OUTPUT // 3
Example 6
You can see in the below example the callback, there is no available greater than 4 value in this collection so it will send the default value.
return collect([1,2,3,4])->last(function($element){ return $element > 4; },111); // OUTPUT // 111
We always thanks to you for reading our blogs.

Dharmesh Chauhan
(Swapinfoway Founder)Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

Haresh Chauhan
(Co-Founder)We Are Also Recommending You :
- How to group routes based on sub-domain laravel?
- Create Custom Route File With New Service Provider Laravel 8 9
- Median() Method | How It is Different From avg() Method In Laravel Collection
- Laravel Delete Image From Storage Folder
- Unique violation: 7 ERROR: duplicate key value violates unique constraint "users_pkey" DETAIL: Key (id)=(1) already exists.
- How To Clone Laravel
- Laravel 10 Create Controller Example
- How To Change ENUM DataType Without Losing Data Laravel Migration
- Laravel Eloquent Parent Child In Same Table With Example
- What are accessors and mutators In Laravel