Join WhatsApp ChannelJoin Now

Random Records from Database in Laravel 10 Example

Hi dev,

Today, i will show you random records from database in laravel 10 example. This article will give you simple example of random records from database in laravel 10 example. you will random records from database in laravel 10 example. In this article, we will implement a random records from database in laravel 10 example.

So, let’s follow few steps to create example of random records from database in laravel 10 example.

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 use the MySQL functions inRandomOrder() and RAND().

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
 <?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 will assist you…

Recommended Posts