Laravel 10 Get Random Record From Database Example

Sovary December 30, 2023 422
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

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him