How to Get Random Records from Database in Laravel - TechvBlogs

How to Get Random Records from Database in Laravel

In this article, You will learn How to Get Random Records from Database in Laravel.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

3 weeks ago

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

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.

Read Also: How to Get only records created today in Laravel

If you want to manage your VPS / VM Server without touching the command line go and  Checkout this linkServerAvatar allows you to quickly set up WordPress or Custom PHP websites on VPS / VM in a  matter of minutes.  You can host multiple websites on a single VPS / VM, configure SSL certificates, and monitor the health of your server without ever touching the command line interface.

If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.

Comments (0)

ServerAvatar
Multiple sites on a single VPS/VM/Server Deploy PHP sites on cloud in minutes, simple as that!
ServerAvatar
Generate Free SSL Certificate - SSLForWeb

Generate Free SSL Certificate

  • 90-Day Certificates
  • SSL Monitoring
  • Wildcard Certificates
  • Multiple Domains
  • Certificate Management
  • Expiration Reminders

Comment


Note: All Input Fields are required.