ItSolutionStuff.com

Laravel Eloquent Order By Random Row Example

By Hardik Savani • April 16, 2024
Laravel

Hello Dev,

In this article, we will cover laravel eloquent order by random. you will learn laravel inrandomorder. I would like to show you laravel random using rand(). We will use laravel orderbyraw mysql function. Let's get started with orderby rand laravel.

You can use this example with laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 versions.

In this post, i will give you simple two ways to get order by random records from database in laravel. we will use inRandomOrder() and RAND() MySQL function to getting random records.

so, let's see both example one by one.

Example 1: Laravel Order By Random Records using inRandomOrder()

you can see the below controller code:

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class UserController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

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

->inRandomOrder()

->get();

dd($users->toArray());

}

}

Example 2: Laravel Order By Random Records using RAND()

you can see the below controller code:

Controller Code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

use DB;

class UserController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index()

{

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

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

->get();

dd($users->toArray());

}

}

I hope it can help you...

Tags: Laravel
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

How to Get Last Executed Query in Laravel 9?

Read Now →

Laravel Eloquent whereHas() Condition Example

Read Now →

Laravel Eloquent Select Single Column to Array Example

Read Now →

Laravel Eloquent Group By with Month and Year Example

Read Now →

Laravel Eloquent When Condition Example

Read Now →

Laravel Eloquent Model Custom Function Example

Read Now →

Laravel Eloquent firstWhere() Example

Read Now →

Laravel Eloquent withSum() and withCount() Example

Read Now →

Laravel Eloquent whereNotNull() Query Example

Read Now →

Laravel Eloquent whereNull() Query Example

Read Now →

Laravel Eloquent whereNotBetween() Query Example

Read Now →

Laravel Eloquent Inner Join with Multiple Conditions Example

Read Now →

Laravel Eloquent Where Like Query Example Tutorial

Read Now →

Laravel Order By with Column Value Example

Read Now →