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 shown 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.
This example works with versions of Laravel 6, Laravel 7, Laravel 8, Laravel 9, and Laravel 10.
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 utilise the MySQL functions inRandomOrder() and RAND().
So, let’s go over both examples in detail.
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());
}
}
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’m Abhishek, a DevOps, SRE, DevSecOps, and Cloud expert with a passion for sharing knowledge and real-world experiences. I’ve had the opportunity to work with Cotocus and continue to contribute to multiple platforms where I share insights across different domains:
-
DevOps School – Tech blogs and tutorials
-
Holiday Landmark – Travel stories and guides
-
Stocks Mantra – Stock market strategies and tips
-
My Medic Plus – Health and fitness guidance
-
TrueReviewNow – Honest product reviews
-
Wizbrand – SEO and digital tools for businesses
I’m also exploring the fascinating world of Quantum Computing.
[…] https://www.devopsconsulting.in/blog/example-how-to-get-random-records-from-database-in-laravel/ […]
[…] Example: How to Get Random Records from Database in Laravel […]