How to Get Random Records in Laravel using Eloquent
In today's lesson, we are going to see an example of how to get random data in Laravel, sometimes when you are working with Laravel you need to get random records using Eloquent to display in a sidebar or anywhere in your blog.
Get random data in laravel using inRandomOrder()
Using the method inRandomOrder() we can retrieve 5 random posts in Laravel as the code shows below:
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
//
public function index(){
$posts = Post::inRandomOrder()->limit(5)->get();
return view('home')->with([
'posts' => $posts
]);
}
}