How To Get Last Record From The Laravel Collection Using last() Collection Method Possible all Example

  • 05-07-2022
  • Laravel 9
  • Haresh Chauhan

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(); 


// 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 

// 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


// 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); 


// 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;


// 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

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


We Are Also Recommending You :