Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Eloquent or Fluent random row

How can I select a random row using Eloquent or Fluent in Laravel framework?

I know that by using SQL, you can do order by RAND(). However, I would like to get the random row without doing a count on the number of records prior to the initial query.

Any ideas?

like image 239
DigitalWM Avatar asked Dec 17 '12 15:12

DigitalWM


People also ask

What is advantage of eloquent in Laravel?

The with function will eager load relations without you having to write the query. That is the advantage of Eloquent, it writes the queries for you. No need to create join queries or extra queries for you.

Is Laravel eloquent slow?

Laracasts VeteranSure it is slow, first it fetch all the record in one time, then it instantiate an eloquent object for each lines. It is not made to retrieve 10 000 objects.

Is eloquent slower than query builder?

Eloquent ORM is best suited working with fewer data in a particular table. On the other side, query builder takes less time to handle numerous data whether in one or more tables faster than Eloquent ORM.

What is meant by eloquent in Laravel?

Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.


1 Answers

Laravel >= 5.2:

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

or to get the specific number of records

// 5 indicates the number of records User::inRandomOrder()->limit(5)->get(); // get one random record User::inRandomOrder()->first(); 

or using the random method for collections:

User::all()->random(); User::all()->random(10); // The amount of items you wish to receive 

Laravel 4.2.7 - 5.1:

User::orderByRaw("RAND()")->get(); 

Laravel 4.0 - 4.2.6:

User::orderBy(DB::raw('RAND()'))->get(); 

Laravel 3:

User::order_by(DB::raw('RAND()'))->get(); 

Check this article on MySQL random rows. Laravel 5.2 supports this, for older version, there is no better solution then using RAW Queries.

edit 1: As mentioned by Double Gras, orderBy() doesn't allow anything else then ASC or DESC since this change. I updated my answer accordingly.

edit 2: Laravel 5.2 finally implements a wrapper function for this. It's called inRandomOrder().

like image 54
aebersold Avatar answered Oct 07 '22 11:10

aebersold