Posts Learn Components new Snippets new Categories Tags About Device Beast sponsor
/

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

Learn how to get random record in Laravel, Make use of eloquent to get the random model and query builder to get random record

Created on Jul 06, 2021

34 views

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.

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Other Code Snippets

More