How7o
  • Home
  • Tools
  • Prank Screens
  • Learn
  • Blog
  • Contact
Reading: How to Retrieve the Last Inserted ID in Laravel Eloquent
Share
How7oHow7o
Font ResizerAa
  • OS
Search
  • Home
  • Tools
  • 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.

FacebookLike
XFollow
PinterestPin
InstagramFollow
Most Popular
Bun runtime — faster JS toolkit replacing npm in Laravel projects
How to Install Bun Runtime on Ubuntu (And Use It in a Laravel Project)
May 24, 2026
Tailscale mesh — peer-to-peer connections between devices, coordination server
How to Install Tailscale on Ubuntu (Zero-Config Mesh VPN for Self-Hosters)
May 24, 2026
Caddy server — automatic HTTPS, 3-line Caddyfile vs 25-line nginx config
How to Install Caddy Server on Ubuntu (Automatic HTTPS, Drop-in nginx Alternative)
May 24, 2026
Cloudflare Tunnel — outbound-only connection from server, no inbound port forward
How to Install Cloudflare Tunnel on Ubuntu (Expose Local Services, No Port Forwarding)
May 24, 2026
WireGuard encrypted tunnel between server and clients with lock icons
How to Set Up WireGuard VPN on Ubuntu (Server, Linux Client, and iOS)
May 24, 2026

You Might Also Like

Get N elements from a JavaScript array with slice for pagination
Web Development

How to Get N Elements from an Array in JavaScript

5 Min Read
Laravel Eloquent current month records — calendar and query builder illustration
Web Development

How to Get Current Month Records in Laravel Eloquent

8 Min Read
Laravel request inputs with prefix — filter request()->all() by Str::startsWith
Web Development

How to Retrieve Inputs with a Specific Prefix in Laravel Request

7 Min Read
Laravel leftJoin to keep all records even without matches
Web Development

How to Use LEFT JOIN in Laravel to Keep All Records

4 Min Read
How7o

We provide tips, tricks, and advice for improving websites and doing better search.

Tools

  • Age Calculator
  • Word Counter
  • Image Upscaler
  • Password Generator
  • QR Code Generator
  • See all tools→

Pranks

  • Fake Blue Screen Prank
  • Hacker Typer
  • Fake iMessage Generator
  • Windows XP Crash Prank
  • Windows 11 Update Prank
  • 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?