Reader Stacks

Laravel Eloquent: Random Rows and the Last Inserted ID

inRandomOrder() and lastInsertId() solve two small, specific problems that come up often enough to be worth knowing by name rather than working out from scratch each time.

Getting a random selection of rows, and retrieving the ID of a record right after inserting it, are two small, specific problems that come up often enough in real applications to be worth knowing the direct Eloquent way to do them.

Getting random rows

$randomProduct = Product::inRandomOrder()->first();

$randomProducts = Product::inRandomOrder()->limit(5)->get();

inRandomOrder() translates to ORDER BY RAND() (MySQL) or the equivalent for your database driver — it performs the randomization in the database itself, rather than pulling every row into PHP and shuffling there, which matters for performance on a table of any real size.

A practical use: featuring a random product on a homepage

public function index()
{
    $featured = Product::where('active', true)->inRandomOrder()->first();

    return view('home', compact('featured'));
}

Why inRandomOrder() can be slow on very large tables

ORDER BY RAND() requires the database to compute a random value for every matching row before sorting — on a table with millions of rows this can become measurably slow, and a more scalable approach (like selecting a random ID range, or maintaining a separate randomized ranking column) is worth considering at that scale, though for typical application-sized tables it's a non-issue.

Getting the ID of a record you just created

$product = Product::create(['name' => 'Widget', 'price' => 19.99]);

echo $product->id; // the newly inserted record's ID, immediately available

Eloquent's create() already returns the fully populated model instance, including its auto-incremented ID — there's no separate "get last insert ID" call needed when using Eloquent, unlike raw PDO or mysqli where retrieving the last insert ID is a distinct, explicit step.

Getting the last insert ID with the raw query builder

$id = DB::table('products')->insertGetId([
    'name' => 'Widget',
    'price' => 19.99,
]);

insertGetId() is the query builder's equivalent when you're not using an Eloquent model — a plain insert() call doesn't return the new ID, but insertGetId() does.

Getting the last insert ID with raw PDO, for context

$pdo->exec("INSERT INTO products (name, price) VALUES ('Widget', 19.99)");
$id = $pdo->lastInsertId();

This is what Laravel's insertGetId() and Eloquent's create() are actually doing under the hood — useful to know if you ever drop down to raw PDO directly, though within a Laravel app there's rarely a reason to bypass the query builder or Eloquent for this.