Laravel 8 Eloquent inRandomOrder() Method Example
In this tutorial, we will learn Laravel 8 Eloquent inRandomOrder() Method Example. We will explain Laravel Eloquent inRandomOrder() Method. We use Laravel its own inRandomOrder() Method functionality to get the random records. This post goes into detail on the Laravel model inrandomorder(). I will give you a very simple example of how to use inRandomOrder() in the Laravel 8 application. In this tutorial, you will learn Laravel 8 Eloquent inRandomOrder() Method Example.
Laravel default provides inRandomOrder() it will help you to get random records from a database table.
Also read: Laravel Eloquent union() Query
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 { public function index() { $users = User::select("*")->inRandomOrder()->first(); /* == OR == */ $users = User::inRandomOrder()->first(); dd($users); } }
SQL with ascending:
select * from users order by RAND() ASC
Laravel Query with ascending:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use DB; class UserController extends Controller { public function index() { $users = User::select("*")->orderBy(DB::raw('RAND()'))->first(); dd($users); } }