In L-4 it was simple:
$random_quote = Quotation::all()->random(1);
But now in L-5 not a single method described in this post is working: Lar
I'd implement this a little differently, using Benjamin's idea. A Query Scope for this feels appropriate so it's reusable, and it falls into your normal Eloquent use.
Note: In Eloquent 5.2, there is built in support for global scopes.
I'm going to create a trait that models can utilize, but you can just add the scopeRandom
method directly to your specific model.
/app/GlobalScopes.php
0 ? mt_rand(0, $totalRows) : 0;
return $query->skip($skip)->take(1);
}
}
Then, each model you want to utilize the global scopes, name the trait inside the class.
/app/Quotation.php
In use:
$randomQuote = \Quotation::random()->first();