get last id form database in laravel-8

I want to get only the last inserted data from my database.
Here, I get all data from the database but I want only the last value.
This is ProductController.php

function indextwo() 
    return DB::select("select * from  products");

This is web.php

Route::get('products_link', [ProductController::class, 'indextwo']);

Here is my current output:

get last id form database in laravel-8


Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can get the last id using Query Builder and Eloquent.

Query Builder

function indextwo() {
    return DB::table('products')->orderBy('id', 'DESC')->first();


function indextwo() {
    return Product::orderBy('id', 'DESC')->first();

Method 2

Maybe you can use latest() function for get

$user = DB::select("select * from  products")

Method 3

Maybe you can use Model name direct in controller like your model name is “Product” and also use limit() and latest()

$user = Products::latest()->limit(1);

Method 4

A very simple way you can follow


It will return you the latest inserted data according to order by id desc.

Another way :


All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x