Example: How to Get Random Records from Database in Laravel

Posted by

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());
    }
}
0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
1
0
Would love your thoughts, please comment.x
()
x