Posts Learn Components new Snippets new Categories Tags About
/

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

Learn how to get or select a random row in Laravel using eloquent or fluent in Laravel the easy way.

Created on Oct 05, 2021

40 views

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();
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻