Laravel Eloquent inRandomOrder() Method Example

By Hardik Savani | July 28, 2020 | 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 just need to some step to done laravel get random row from table.

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
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.

We are Recommending you: