loading...

How To Get Last Inserted Record In Laravel?

pakainfocom profile image pakainfo ・1 min read

I have “products” DB table as well as i want to fetch the last row or DB record of “products” table. In simple example i use the Laravel function latest() with first() so latest() will fetch single latest row according to created_at after that first() will get single record how to get last inserted record in laravel?:

Using Latest() Belong To Created_at Field:

$get_last_record = DB::table('products')->latest()->first();
dd($get_last_record);

To get last record details
Product::all()->last();
//or
Product::orderBy('id', 'desc')->first();

Way 1:

public function getLastInsertedId()
{
$id = DB::table('products')->insertGetId(
['pcode' => 'p9825656', 'name' => 'Mobile']
);

dd($id);
}

There are the 5+ ways to how to get last inserted record in laravel?

Posted on by:

pakainfocom profile

pakainfo

@pakainfocom

My name is Angular King. I'm a full-stack developer, entrepreneur and owner of Pakainfo. I live in India and I love to write

Discussion

pic
Editor guide