Random Model Scope

Submitted by david - 3 years ago

Here's a simple little scope that you can use to get a random collection of Model objects from the database.

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

// In your code, you can use it with your other scopes like this:
$users = User::popular()->random()->get();

Ads cover the costs of maintaining Laravel-tricks

comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks