How7oHow7o
  • Home
  • Tools
    • All Tools
    • Image Tools
    • Text & String Tools
    • Video Tools
    • Developer Tools
    • PDF Tools
    • Calculators & More
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Retrieve the Last Inserted ID in Laravel Eloquent
Share
Notification Show More
Font ResizerAa
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
    • All Tools
    • Image Tools
    • Text & String Tools
    • Video Tools
    • Developer Tools
    • PDF Tools
    • Calculators & More
  • Prank Screens
  • Learn
  • Blog
  • Contact
Follow US
© 2024–2026 How7o. All rights reserved.
How7o > Free Laravel, PHP, WordPress & Server Tutorials > Web Development > How to Retrieve the Last Inserted ID in Laravel Eloquent
Web Development

How to Retrieve the Last Inserted ID in Laravel Eloquent

how7o
By how7o
Last updated: April 20, 2026
8 Min Read
Laravel last inserted ID — Eloquent save populates model primary key illustration
SHARE

Retrieving the laravel last inserted id sounds like one question but has two very different answers depending on context: if you just inserted the row, Eloquent already handed you the ID on the model instance; if you need the latest record in a table without having inserted it yourself, the right pattern is latest('id')->first(). This guide walks through both paths, flags the Model::all()->last() anti-pattern that silently scales to millions of rows, and covers the raw-PDO fallback for edge cases.

Contents
  • TL;DR
  • If you just inserted the row, use the instance
  • If you need the latest record, use latest / orderBy
  • Anti-pattern: Model::all()->last() / Model::get()->last()
  • Query builder: insertGetId()
  • Raw PDO fallback: DB::getPdo()->lastInsertId()
  • Frequently asked questions
  • Related guides
  • References

Last verified: 2026-04-21 on Laravel 11 with PHP 8.3 and MySQL 8.0. Originally published 2024-03-17, rewritten and updated 2026-04-21.

TL;DR

Just inserted? Read $model->id from the saved instance — save() and create() populate it for you. Need the most recent row without having inserted it? Use Model::latest('id')->first() or equivalently Model::orderBy('id', 'desc')->first(). Never use Model::all()->last() or Model::get()->last() — they load every row into memory first.

If you just inserted the row, use the instance

The standard, idiomatic path: when you insert through Eloquent, the returned model already has its primary key set. No extra query needed.

$post = Post::create([
    'title' => 'Hello',
    'body'  => '...',
]);

$id = $post->id;   // auto-populated by Eloquent

Same with manual saves:

$post = new Post();
$post->title = 'Hello';
$post->save();

$id = $post->id;

This is the pattern you should reach for 99% of the time. Issuing a second SELECT to fetch an ID you just wrote is wasted work and introduces a race condition if concurrent inserts are possible.

If you need the latest record, use latest / orderBy

Different problem: you’re an admin dashboard, background job, or second request, and you want the most recent row in a table. Four equivalent forms all compile to ORDER BY id DESC LIMIT 1:

Model::orderBy('id', 'desc')->first();
Model::latest('id')->first();
Model::latest('id')->limit(1)->get();
Model::orderBy('id', 'desc')->limit(1)->get();

latest('id') is syntactic sugar for orderBy('id', 'desc'). Both ->first() and ->limit(1)->get() return exactly one database row; the difference is first() returns a single model (or null), while get() returns a Collection containing one model. Use first() unless downstream code already expects a Collection.

For the oldest row, flip the direction:

Model::orderBy('id', 'asc')->first();
laravel last inserted id — latest() first() versus all() last() memory comparison

Anti-pattern: Model::all()->last() / Model::get()->last()

This looks innocent and returns the right answer on a small table:

// DO NOT DO THIS
Post::all()->last();
Post::get()->last();

The problem is where the last() happens. all() issues a SELECT * with no LIMIT, hydrates every row into an Eloquent model inside a Laravel Collection, and then Collection’s last() picks the last element in PHP. On a production table with a million rows, that’s a million hydrated models to read one ID — the query that was 2 ms becomes 30 seconds and an out-of-memory crash.

The fix is to push the “last” into SQL via ORDER BY ... DESC LIMIT 1, which is exactly what latest('id')->first() does.

Query builder: insertGetId()

Not using Eloquent and writing through the query builder instead? Use insertGetId() — it runs the insert and returns the new auto-increment ID in one call:

$id = DB::table('posts')->insertGetId([
    'title'      => 'Hello',
    'body'       => '...',
    'created_at' => now(),
    'updated_at' => now(),
]);

No separate SELECT, no race conditions. If your insert has a different primary key column, pass it as the second argument: insertGetId($data, 'uuid').

Raw PDO fallback: DB::getPdo()->lastInsertId()

For the rare case where you ran a raw DB::insert or executed a prepared statement through DB::statement and can’t rework the code to use Eloquent or insertGetId:

DB::insert('insert into posts (title, body) values (?, ?)', ['Hi', '...']);
$id = DB::getPdo()->lastInsertId();

PDO’s lastInsertId() returns the auto-increment value generated by the most recent INSERT on the same connection. It works for MySQL, MariaDB, PostgreSQL (with a sequence name) and SQLite. The connection-scope caveat matters: if your code switches connections between the insert and the read, you’ll get the wrong value or zero.

Frequently asked questions

What’s the cleanest way to get the laravel last inserted id after create()?

If you’re the one inserting the row, don’t query again — use the instance. $post = Post::create($data); $id = $post->id; works because Eloquent populates the primary key on the returned model. Same with manual saves: $post = new Post(); $post->save(); $id = $post->id;.

When should I use latest('id')->first() versus orderBy('id', 'desc')->first()?

They’re equivalent — latest('id') is a readable alias that compiles to ORDER BY id DESC. Use latest('id')->first() for style; reach for orderBy('id', 'desc')->first() when the explicit direction reads better next to other ordering clauses in the same query.

Why shouldn’t I use Model::all()->last() or Model::get()->last()?

Because both pull every row out of the database, hydrate them into a Laravel Collection in PHP memory, and then pick the last element. On a table with a million rows that’s a million hydrated models just to read one ID. latest('id')->first() asks MySQL for exactly one row — the fast, scalable query.

How do I get the last inserted ID from a raw DB::insert?

The query builder’s DB::table('posts')->insertGetId($data) returns the new auto-increment ID directly. If you ran a raw DB::insert statement yourself, fall back to PDO: DB::getPdo()->lastInsertId(). It works on MySQL, PostgreSQL and SQLite as long as the connection used to execute the insert is the same one you call lastInsertId() on.

Is it safe to use max('id') to find the latest record?

Only if IDs are strictly increasing and no rows were inserted out of order — which is usually true for standard auto-increment columns. Model::max('id') returns the scalar max, so you still need a second query to hydrate the record. latest('id')->first() is one round-trip and returns the full model; prefer it.

Related guides

  • How to Install Laravel on Ubuntu — set up Laravel 11 before you query anything.
  • Best Way to Insert or Update Records in Laravel Eloquent — upsert patterns that also populate $model->id.
  • How to Check if a Record Exists in Laravel — when you only need existence, not the ID.
  • Laravel Eloquent orderBy — the ordering clause latest() is sugar for.

References

Official Laravel Eloquent docs (inserts, ordering, retrieving models): laravel.com/docs/eloquent. Query builder insertGetId and ordering: laravel.com/docs/queries.

TAGGED:EloquentLaravelmysqlphp

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
[mc4wp_form]
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Copy Link Print
Previous Article Laravel Eloquent records today — Carbon today helper and whereDate illustration How to Get Records Created Today in Laravel
Next Article Laravel left outer join — query builder leftJoin illustration with two tables How to Do a Left Outer Join in Laravel Query Builder
Leave a Comment

Leave a Reply Cancel reply

You must be logged in to post a comment.

You Might Also Like

Reload DataTables with a new Ajax URL
Web Development

How to Reload DataTables with a New Ajax URL

4 Min Read
Check Bootstrap modal open or closed with jQuery
Web Development

How to Check if a Bootstrap Modal Is Open or Closed with jQuery

4 Min Read
Remove unwanted characters from a PHP string with regex
Web Development

How to Remove Unwanted Characters from a String in PHP

5 Min Read
Laravel Blade @foreach vs @forelse comparison
Web Development

Laravel Blade: Difference Between @foreach and @forelse

4 Min Read
How7oHow7o

Free browser-based tools, prank screens, and step-by-step tech tutorials. No signup, nothing uploaded.

  • Private by design — your files never leave your device
  • Instant — no signup, no install, no waiting
  • Always free — no trials, no watermarks, no paywalls

Tools

  • PDF Editor
  • Image Upscaler
  • JPEG Compressor
  • Password Generator
  • QR Code Generator
  • Video Trimmer
  • See all tools →

Pranks

  • Cracked Screen Prank
  • Fake Blue Screen (BSOD)
  • Fake Disk Format
  • Fake Low Battery
  • Fake Virus Scan
  • Fake Windows 10 Update
  • See all prank screens →

Company

  • About Us
  • Blog
  • Contact
  • Privacy Policy
  • Terms of Service
  • Sitemap
© 2024–2026 How7o. All rights reserved.
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?