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 :
- Different Solutions For Fix 419 Page Expired laravel
- Laravel Email Send
- Force Redirect to www From Non-www Using htaccess In Laravel
- How To Get Youtube Video Thumbnail From URL In PHP - Laravel
- How To Add Google reCAPTCHA v3 In HTML Form Based PHP/Laravel Website
- How to hide image URL from IMG tag src laravel
- UPI Payment Gateway Integration in PHP/Laravel
- Bootstrap 5 Modal Not Working Blade File Laravel
- How To Filter/Search Single Column Multiple Id Stored Laravel
- How To Add Google reCAPTCHA v2 In HTML Form Based PHP/Laravel Website