How7o
  • Home
  • Tools
  • Prank Screens
  • Contact
  • Blog
Reading: How to Retrieve the Last Inserted ID in Laravel Eloquent
Share
Subscribe Now
How7oHow7o
Font ResizerAa
  • Marketing
  • OS
  • Features
  • Guide
  • Complaint
  • Advertise
Search
  • Home
  • Tools
  • Prank Screens
  • Contact
  • Blog
Follow US
Copyright © 2014-2023 Ruby Theme Ltd. All Rights Reserved.
How7o > Blog > 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.
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

Subscribe Now

Subscribe to our newsletter to get our newest articles instantly!
Most Popular
Laravel left outer join — query builder leftJoin illustration with two tables
How to Do a Left Outer Join in Laravel Query Builder
April 20, 2026
Laravel last inserted ID — Eloquent save populates model primary key illustration
How to Retrieve the Last Inserted ID in Laravel Eloquent
April 20, 2026
Laravel Eloquent records today — Carbon today helper and whereDate illustration
How to Get Records Created Today in Laravel
April 20, 2026
Laravel Eloquent current month records — calendar and query builder illustration
How to Get Current Month Records in Laravel Eloquent
April 20, 2026
Laravel Eloquent group by count — Book::groupBy('author') query with bar-chart aggregate icon
How to Count Records Grouped By a Column in Laravel Eloquent
April 20, 2026

You Might Also Like

Debug PHP like console.log using error_log and server logs
Web Development

How to Debug in PHP Like console.log (echo, error_log, WordPress debug.log)

6 Min Read
Laravel migration adding two new columns to an existing transactions table
Web Development

How to Add New Columns to an Existing Table in Laravel Migration

5 Min Read
How I Fixed Composer Dependency Errors
Web Development

How I Fixed Composer Dependency Errors Using the –ignore-platform-reqs Flag (Step-by-Step Guide)

7 Min Read
Login to Laravel programmatically without a password (Auth::login and loginUsingId)
Web Development

Login to Laravel Programmatically Without a Password (Auth::login & loginUsingId)

4 Min Read
How7o

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

Latest News

  • SEO Audit Tool
  • Client ReferralsNew
  • Execution of SEO
  • Reporting Tool

Resouce

  • Google Search Console
  • Google Keyword Planner
  • Google OptimiseHot
  • SEO Spider

Get the Top 10 in Search!

Looking for a trustworthy service to optimize the company website?
Request a Quote
Welcome Back!

Sign in to your account

Username or Email Address
Password

Lost your password?