Launching Drycomponents - Get Free HTML/React Components built using TailwindCSS

Laravel Tips : Eloquent last() method

While I was going through twitter feed recently, I happen to see a tweet from @calebporzio about the need of last() method in Eloquent just like the way we have first() method. This is so true that even I myself wanted the same functionality while working on many of my freelance projects. So I thought I would blog about its implementation

Simple way

One of the easiest way to achieve this is, create a static method on your model file like the following and you are good to go.

Long but recommended way

The better way to implement the same functionality would be create a new model file and extending the core model file on it. And then letting our Post model extend our newly created model rather than Laravel's Eloquent model. This way, last() method can be easily added to any model by simply swapping the default laravel model it is extending. Plus, in future if you need to add any new functionality that needs to be available across all models, it can be written here. As easy as that.

Would like to hear more from me?

Consider Signing up. No spam ever.