Wednesday, December 25, 2024
Google search engine
HomeLanguagesHow 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.

RELATED ARTICLES

Most Popular

Recent Comments