Laravel Tip: Random Model Scopes

Published: January 14, 2014

In Laravel, there is the concept of Query Scopes which allow you to re-use logic in your queries for getting things such as, say, active members, or male users.

I was needing to get a randomized set of Users for a project I was working on and came up with this dead-simple way of doing that using a random() scope.

I simply made a scope on my User model with the following:

/**
 * Get random users
 */
public function scopeRandom($query)
{
    $query->orderBy(DB::raw('RAND()'));
}

This allows me to reuse this logic instead of putting it in the controller each time. I can easily get a set of random user like this:

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

Hope that helps!

David Hemphill

About David Hemphill

Builder of web things. Family man. I used to fight. I used to music. I'm an introvert, but I still like you.