Laravel get Random Record from Model Example
Sep 28, 2022 . Admin
Hello Friends,
Here, I will show you the laravel get random record from the model example. let’s discuss laravel's eloquent get random record code example. we will help you to give an example of laravel's eloquent inrandomorder() method example. I explained simply step by step how to get random records in laravel.
You must be visiting many blogs. So sometimes you have to see these blogs in the sidebar. It is written in random posts and there are some posts below it.
If you are building a blog application in the laravel framework. And want to get random posts/data from the database in laravel. And want to display this random data anywhere on your laravel blog. So at that time, you need to use inRandomOrder() method to get random records in laravel.
This article will guide you on how to use get random records from the database in laravel using inRandomOrder() method. As well as get random records from a collection in laravel.
You can use this example with the versions of laravel 6, laravel 7, laravel 8, and laravel 9.
You can see bellow default route for login post method:
Step 1: Install Laravelfirst of all we need to get a fresh Laravel version application using the bellow command, So open your terminal OR command prompt and run the bellow command:
composer create-project laravel/laravel example-appStep 2: create RandomrecordController
we will create RandomrecordController with inRandomOrder() method. so you can see the below code with output:
php artisan make:controller RandomrecordControllerApp\Http\Controllers\RandomrecordController
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class RandomrecordController extends Controller { /** * The attributes that are mass assignable. * * @var array */ public function index() { $data = DB::table('posts') ->select('posts.id','posts.name','posts.title') ->inRandomOrder() ->limit(5) ->get(); dd($data->all()); } }Step 3: Create Random Route web.php
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\RandomrecordController; /* |-------------------------------------------------------------------------- | 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('random', [RandomrecordController::class, 'index']);Start Development Server
Start the development server. Use the PHP artisan serve command and start your server:
php artisan serve
Now you are ready to run our example so run the below command to quick run.
http://localhost:8000/random
It will help you...