How Do I Get Random Records in Laravel?

Sovary October 10, 2022 727
3 minutes read

Today article we will discussion about how to get records randomly in Laravel and give a very simple example of eloquent method to get random record in Laravel. You can see how we get random record from model using eloquent in Laravel. This post will show you step by step with example of Laravel eloquent randomorder() method to get data randomly. Let's look at below example how we retrieve data randomly.

I believe you have seen many blogs post in sidebar there are randomly post suggest to you. Some wordpress or other CMS have the widget to show random post but today we can get randomly records in Laravel as well.

If you want to retrieved records randomly from database in Laravel framework, you will suggest to use eloquent method in Laravel call inRandomOrder() method which will return records data unordering so you can display that randomly anywhere on your laravel posts. The below step will help you to implement how to retrieved data from database randomly in Laravel using inRandomOrder() method. .You can use this example with the Laravel 6, Laravel 7, Laravel 8, and Laravel 9.

How to get Random Records

  • Step 1 - Install Laravel
  • Step 2 - Create Model Migration
  • Step 4 - Create Controller
  • Step 5 - Add Routes
  • Step 6 - Run Laravel Server

Step 1 - Install Laravel

We will download latest Larave application by using below command, so launch the terminal and run the command below. Anyway we still need database connection. Read this to know how to install Laravel project and configure database connection.

composer create-project laravel/laravel blog

Step 2 - Create Model Migration

Create Model

Example here we are going to build an News application which will contain a table Article to store all posts data, so we are going to create a model class and migration file. To generate migration at the same time generate the model, you may use the --migration or -m option. Let's run following command:

php artisan make:model Article -m

Open file app -> models -> article.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    use HasFactory;

    protected $fillable = [
        'title', 'body'
    ];
}

Update Migration

Open file database -> migrations -> 2022_10_10_033254_create_articles_table.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
};

Before run command migrate to generate table in database, go to update in app service provider file with limit string length.

Open file app -> Providers -> AppServiceProvider.php

use Illuminate\Support\Facades\Schema;

/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    Schema::defaultStringLength(191);
}

Then run following command in terminal to generated table in database:

php artisan migrate

Step 4 - Create Controller

We are going to create new controller file call RandomController with followoing command

php artisan make:controller RandomController

Open file App -> Http -> Controllers-> RandomController

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class RandomController extends Controller
{
   
    public function index()
    {
        $data = Article::select('id','title','description')
                    ->inRandomOrder()
                    ->limit(15)
                    ->get();
        dd($data->all());
    }
}

Step 5 - Add Route

This step we will add route link to get random record from controller

Open file routes -> web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\RandomController;


/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', [RandomController::class, 'index']);

Now we do not need blade file html because we use dd() method to print out the array, so we are going to start Laravel server by following command

php artisan serve

 Then we will see first home page laravel project via http://localhost:8000/ you will see the array print out randomly.

You might also like...

Laravel  PHP  Laravel 9  Query Builder 
Author

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