How to get records in random order in laravel

Updated at 19-Aug-2021, By samar

How to get records in random order in laravel

In this session, we will try our hand at solving the "How to get records in random order in laravel".

You can get the records in random order from a table in laravel. Laravel uses the inRandomOrder() method on eloquent collection to get the records in random order.
  • Get records from user table in random order using inRandomOrder() in laravel

    $users = User::inRandomOrder()->get();
    
    

    Step by step code implementation

    routes\web.php

    use App\Http\Controllers\HomeController;
    Route::get('/get-data-in-random-order', [HomeController::class, 'getDataInRandomOrder']);
    

    //Create HomeController using artisan command

    php artisan make:controller HomeController

    
    
    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Models\User;
    
    class HomeController extends Controller
    {
        
        public function getDataInRandomOrder(){
            $users = User::select('id', 'name')->inRandomOrder()->get();
            echo "<pre>";
            print_r($users);
        }
    }
    

    You can get all the records from the user table in Laravel in random order. This code snippet will return all the records in a different order on each reload of the page.

  • Raw expression to get random records in laravel

    $users = User::orderBy(DB::raw('RAND()'))->take(10)->get();
    //Or
    $users = User::orderByRaw('RAND()')->take(10)->get();
    

    You can get the records from users table in random order by using raw expressions. 

Back to code snippet queries related laravel