12-May-2023
.
Admin
Hi dev,
Let's look at a lesson on getting records in random order in Laravel right away. You'll find a straightforward example of how to acquire a random record from a model in this post. Laravel may be seen obtaining random data from a database. We will assist you by providing a sample of how to retrieve a random record from a database using Laravel.
You can use this example with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 versions.
I'll show you two straightforward methods in this post for ordering random records from a database in Laravel. To obtain random records, we will use the MySQL functions inRandomOrder() and RAND().
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...
#Laravel 10