Let's explore a lesson on fetching records in a random order in Laravel. This post contains a straightforward example that illustrates the process of query a random record from a model. Laravel has the function to retrieve random data from a database, and we are here to assist you by providing a sample code snippet that demonstrates how to retrieve a random record using Laravel.
We can use this example with laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 versions.
I'll show you two methods in this post to get random records from a database in Laravel. To make random records, we will use the MySQL functions inRandomOrder() and RAND().
Suppose you have created controller file then open the controller file.
php artisan make:controller TestController
Open file app -> Http -> Controllers -> TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class TestController extends Controller
{
public function index()
{
$users = User::select("*")
->inRandomOrder()
->get();
dd($users->toArray());
}
}
Open file app -> Http -> Controllers -> TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
use DB;
class UserController extends Controller
{
public function index()
{
$users = User::select("*")
->orderBy(DB::raw('RAND()'))
->get();
dd($users->toArray());
}
}
Hope this article help you to retrieved random data. Have a nice day!
You may also like...
As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him