How to Get Random Records in Laravel

How to Get Random Records in Laravel

Laravel get a random record example. Here you will learn how to get random records from DB in laravel using inRandomOrder() method.

You must be visiting many blogs. So sometimes you have seen these blogs in the sidebar. It is written random posts and there are some posts below it.

If you are building a blog application in laravel framework. And want to get random posts/data from the database in laravel. And want to display this random data anywhere on your laravel blog. So at that time, you need to use inRandomOrder() method to get random records in laravel.

This article will guide you on how to use get random records from the database in laravel using inRandomOrder() method. As well as get random records from collection in laravel.

Note that, Laravel inRandomOrder method may be used to sort the query results randomly. For example, if you want to get random posts from DB in laravel. So you can use the below following methods as well.

1: Laravel Retrieve Random Records From DB with Eloquent

The following example will fetch the 5 random posts from DB table in laravel:

/**
* The attributes that are mass assignable.
*
* @var array
*/
public function index()
{
    $data = DB::table('posts')
                ->inRandomOrder()
                ->limit(5)
                ->get();
}

2: Laravel Retrieve Random Records From DB using Model

The following method also will fetch the 5 random posts from DB table in laravel:

/**
* The attributes that are mass assignable.
*
* @var array
*/
public function index()
{
    $data = Post::inRandomOrder()
                ->limit(5)
                ->get();
}

Conclusion

In this laravel fetch random records from database or collection, you have learned how to get random records from database and collection using inRandomOrder() method in laravel framework.

Recommended Laravel Posts

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

One reply to How to Get Random Records in Laravel

  1. Hi, Devendra Dode, how are you? I m new in Laravel deployment apps.
    Is possible to talk with you way whatsapp or email for a help and others subjects? My email is [email protected]

    1. Is possible to get random records in laravel BUT of USERs? like is the code for this?

    2. Is possible to mix features of 2 or more laravel apps of differents proyect? like is possible this? like will be with API REST? or MIX DATABASE?

Leave a Reply

Your email address will not be published. Required fields are marked *