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 :
- Pinelabs Payment Gateway Integration Tutorial In Laravel
- Laravel Custom Command Make Example
- groupBy() Method Laravel Collection Exmaple
- Laravel 9 Create Custom Auth Guard Multi Login Authentication System Tutorial
- myfatoorah Payment Gateway Integration Laravel
- Single Session User Login in Laravel
- How To Convert HTML To Image/PDF Using Snappy In Laravel 9
- How To Generate A Sitemap In Laravel 6/7/8/9
- Laravel 9 QR Code Generator Basic To Advanced Tutorial Example
- Call to undefined function Gregwar\Captcha\imagecreatetruecolor()