How to Retrieve the Last Inserted ID from a Specific Table Using Laravel?

I’m in a situation where data is inserted in one method, and I need to access the ID of the last inserted row in a different method of a different controller. I need to retrieve the ID from that table. How can I accomplish this in Laravel?
I have tried this but not sure if this is appropriate or not.


Using Model::get()->last() or Model::all()->last() to retrieve the most recent entry from a database table is not recommended due to its inefficiency. These methods fetch all records from the table, potentially causing performance issues, especially with large datasets. It’s akin to searching through an entire library for just one book. This approach can strain server resources unnecessarily, leading to slower response times, particularly when handling high traffic volumes.

Here are some recommended alternatives:

// Retrieving the most recent record
Model::orderBy('id', 'desc')->first(); // Preferred method
Model::latest('id')->first(); // Another preferred method
Model::latest('id')->limit(1)->get(); // Alternative method
Model::orderBy('id', 'desc')->limit(1)->get(); // Alternative method

// Retrieving the oldest record
Model::orderBy('id', 'asc')->first(); // Preferred method
Model::orderBy('id', 'asc')->limit(1)->get(); // Alternative method
Model::orderBy('id', 'asc')->first(); // Alternative method