Hey Friends,Hey Dev,
Today, I would like to show you how to get records in random order in laravel. It's a simple example of laravel get random record from model. It's a simple example of laravel get random data from database. If you have a question about laravel get random record from database then I will give a simple example with a solution.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 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()
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...
Do you like below Tutorials ?
- Multidimensional Array Search By Value in PHP
- Laravel Install Font Awesome Icons Example
- How to Use Moment JS in Laravel?
- Angular 9 Get Environment Variables Example
- Angular Delete a Component From Cli Example
- How to Upload File from Local to Server using SSH?
- Angular Use CKEditor Example Tutorial
- How to Use Multiple Select Dropdown in Laravel?