Hello there! Welcome to our blog where we’ll explore how to retrieve records in random order using Laravel.
In this article, we’ll provide you with a simple example of fetching random records from a database in Laravel. You can apply this technique in Laravel versions 6, 7, 8, 9, and 10.
Let’s dive into two different approaches to achieve this.
Example 1: Laravel Order By Random Records using inRandomOrder()
Here’s an example of the controller code you can use:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
/**
* Get random records from the user table.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::select("*")
->inRandomOrder()
->get();
dd($users->toArray());
}
}
Example 2: Laravel Order By Random Records using RAND()
Here’s another example of the controller code you can utilize:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use DB;
class UserController extends Controller
{
/**
* Get random records from the user table.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$users = User::select("*")
->orderBy(DB::raw('RAND()'))
->get();
dd($users->toArray());
}
}
We hope this tutorial proves helpful to you. Feel free to reach out if you have any further questions or require additional assistance. Happy coding!