Laravel 10 Get Random Record From Database Example

Sovary December 30, 2023 401
1 minute read

Let's explore a lesson on fetching records in a random order in Laravel. This post contains a straightforward example that illustrates the process of query a random record from a model. Laravel has the function to retrieve random data from a database, and we are here to assist you by providing a sample code snippet that demonstrates how to retrieve a random record using Laravel.

We can use this example with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 versions.

I'll show you two methods in this post to get random records from a database in Laravel. To make random records, we will use the MySQL functions inRandomOrder() and RAND().

Example 1: using inRandomOrder()

Suppose you have created controller file then open the controller file.

php artisan make:controller TestController

Open file app -> Http -> Controllers -> TestController.php

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\User;
    
class TestController extends Controller
{

    public function index()
    {
        $users = User::select("*")
                        ->inRandomOrder()
                        ->get();
    
        dd($users->toArray());
    }
}	

 

Example 2: using RAND()

Open file app -> Http -> Controllers -> TestController.php

<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\User;
use DB;
    
class UserController extends Controller
{

    public function index()
    {
        $users = User::select("*")
                        ->orderBy(DB::raw('RAND()'))
                        ->get();
    
        dd($users->toArray());
    }
}

Hope this article help you to retrieved random data. Have a nice day! 

You may also like...

Laravel  PHP  Laravel 10 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him