How to Get Random Records from Database in Laravel

Hello Geek, When developing a project, we may need to display random data on the frontend. To do so, we must retrieve random records from the database and display them on the frontend. There are some methods in Laravel for retrieving random records from a database.

This article will demonstrate how to retrieve random records from a database.

How to Get Random Records from Database in Laravel

Laravel >= 5.2

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

You can also use this method to get limited random records if you want 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();

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();

All the best nerd!

Leave a Reply