ItSolutionStuff.com

Laravel Eloquent inRandomOrder() Method Example

By Hardik Savani • April 16, 2024
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...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel Eloquent whereNotBetween() Query Example

Read Now →

Laravel Eloquent orderByRaw() Query Example

Read Now →

Laravel Eloquent whereRaw Condition Example

Read Now →

How to Group By with Order By Desc in Laravel?

Read Now →

Laravel Order By Relation Column Example

Read Now →

Laravel Order By Relationship Sum Column Example

Read Now →

Laravel Where Condition with Two Columns Example

Read Now →

Laravel Where Clause with date_format() Example

Read Now →

Laravel Eloquent Order By Random Row Example

Read Now →

Laravel Order By with Column Value Example

Read Now →