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.

Answers 2
  • Get records from user table in random order using inRandomOrder() in laravel

    $users = User::inRandomOrder()->get();
    //Step by step code implementation
    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
    //HomeController with method
    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>";

    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();
    $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