How to Get Random Records from Database in Laravel?
Hey Friends,
Now, let's see a tutorial of how to get records in random order in laravel. This article will give you a simple example of laravel get random record from model. you can see laravel get random data from database. we will help you to give an example of laravel get random record from database.
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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. 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, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel 9 Many to Many Eloquent Relationship Tutorial
- Laravel Eloquent without() and withOnly() Method Example
- Laravel Eloquent doesntHave() Condition Example
- Laravel Eloquent orWhereHas() Condition Example
- Laravel Eloquent whereRelation() Condition Example
- Laravel Eloquent whereHas() Condition Example
- Laravel Eloquent Select Single Column to Array Example
- Laravel Eloquent Group By Year with Sum Example
- Laravel Eloquent Model Custom Function Example
- Laravel Eloquent withMin(), withMax() and withAvg() Example
- Laravel Eloquent withSum() and withCount() Example
- Laravel Eloquent updateOrCreate Example
- Laravel Eloquent Where Like Query Example Tutorial
- How to Get Query Log in Laravel Eloquent?