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();
<?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();
<?php User::orderBy(DB::raw('RAND()'))->first();
Leave a reply