Home / Snippets / How to Get a Random Row in Laravel Using Eloquent or Fluent
How to Get a Random Row in Laravel Using Eloquent or Fluent cover

How to Get a Random Row in Laravel Using Eloquent or Fluent

575

3 years ago

0 comments

To randomly get a record in Laravel you can make use of the "inRandomOrder()" method available to all of your model instances.

Using inRandomOrder()


For example, if you want to get a random user you can write the following code and it will return one random user.
<?php

User::inRandomOrder()->get();

Using Collection random() method


The 2nd way is to use the "random()" method of the collection instance and this way will retrieve all of the records and randomly get the record/instance.
<?php

User::all()->random();
Do note you can pass in how much record/instance by passing the number of records to the "random()" method.
<?php

User::all()->random(10);

Using orderByRaw() method


The 3rd way is to use "orderByRaw()" method and it will accept raw SQL function. If you are using PostgreSQL then the raw SQL function will be "'RANDOM()'"
<?php

User::orderByRaw("RAND()")->first();
One other way to write the code above is as follows.
<?php

User::orderBy(DB::raw('RAND()'))->first();
notion avatar

Alaz

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 ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this