Laravel Eloquent inRandomOrder() Method Example

By Hardik Savani April 16, 2024 Category : Laravel

This tutorial shows you laravel inRandomOrder example. i would like to show you laravel eloquent inrandomorder. This article goes in detailed on laravel model inrandomorder. This article will give you simple example of laravel get random record.

You can get random row from table in laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 application.

In this example i will give you very simple example of how to use inRandomOrder() in laravel application. you can easily use it with laravel 6 and laravel 7 application.

inRandomOrder() will help you to get random records from database table.

So, let's see bellow examples that will help you how to use random records in laravel.

Example: inRandomOrder()

SQL Query:

select * from `users`

order by RAND()

Laravel Query:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$users = User::select("*")

->inRandomOrder()

->first();

dd($users);

}

}

Example 2

SQL Query:

select * from `users`

order by RAND() asc

Laravel Query:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

use DB;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index()

{

$users = User::select("*")

->orderBy(DB::raw('RAND()'))

->first();

dd($users);

}

}

I hope it can help you...

Shares