How to Get Random Records from Database in Laravel

Smit Pipaliya
TechvBlogs
Published in
1 min readOct 2, 2022

Sep 11, 2022, Originally published at techvblogs.com ・1 min read

In the project development sometimes we need to display random data on Frontend that time we need to fetch random records from the database to display random records on the frontend. In Laravel, There are some methods to get random records from the database.

This article will teach you how to get random records from the database.

How to Get Random Records from Database in Laravel

Laravel >= 5.2

Post::select('id', 'title' ,'slug')->inRandomOrder()->get();

Also, If you want to get limited random records then you can use this method to get limited random records.

// Random Record with a limit
Post::select('id', 'title' ,'slug')->inRandomOrder()->limit(10)->get();
// Single Random Record
Post::select('id', 'title' ,'slug')->inRandomOrder()->first();

{{ADD_HERE}}

Laravel 4.2.7–5.1

Post::select('id', 'title' ,'slug')->orderByRaw("RAND()")->get();

Laravel 4.0–4.2.6

Post::select('id', 'title' ,'slug')->orderBy(\DB::raw('RAND()'))->get();

Laravel 3

Post::select('id', 'title' ,'slug')->order_by(\DB::raw('RAND()'))->get();

That’s it.

These are the simplest methods to get random records from the database.

Thank you for reading this article.

--

--

Smit Pipaliya
TechvBlogs

I am Project Manager at ServerAvatar Cloud Technology.