Home / Snippets / How to Get Random Record in Laravel using Query Builder and Eloquent Model
How to Get Random Record in Laravel using Query Builder and Eloquent Model cover

How to Get Random Record in Laravel using Query Builder and Eloquent Model

1.9K

2 years ago

0 comments

There are 2 ways to get a random record in Laravel. You can make use of Laravel query builder as well as an eloquent model but either way you have to call the "inRandomOrder" method.

Using Query Builder
$randomUser = DB::table('users')
                ->inRandomOrder()
                ->first();

Using Eloquent Model
$randomComment = Comment::query()
                ->inRandomOrder()
                ->first();

Both of the queries above will return a random record.
notion avatar

Ahmad Aziz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Post Tutorials

Learn trending tutorials for ReactJs, React Native, VueJS, NextJs, Laravel, Tailwind CSS, and Flutter development.
View Tutorials

Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your web projects
View Components

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this