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
These works but probably you didn't use the right namespace
, just use the use
statement at the top of your class
name like this:
<?php namespace SomeNamespace;
use App\Quotation; // Says "Quotation.php" is in "App" folder (By default in L-5.0)
class someClass {
//...
}
Then you may use in your method
something like this:
// You may add: use DB; at the top to use DB instead of \DB
$random_quote = Quotation::orderBy(\DB::raw('RAND()'))->first();
Or this:
$random_quote = Quotation::orderByRaw("RAND()")->first();
Update (Since Laravel - 5.2):
$random_quote = Quotation::inRandomOrder()->first();
UPDATE FOR LARAVEL 5.3
I was happy to discover this is now a native query function! :D
The inRandomOrder
method may be used to sort the query results randomly. For example, you may use this method to fetch a random user:
$randomUser = DB::table('users')
->inRandomOrder()
->first();
Unfortunately none of these answers make full use of Laravel 5's collections. If you came here from Google, like me, looking for a completely native solution please look below!
The Answer from The Alpha has the Database dependency flaw and Benjamin's, as he pointed out, may pose a problem when rows are removed in between. Highly unlikely, but still possible.
Here's a a one line solution to select random rows in Laravel 5+
// The setup
$numberOfRows = 4;
$models = Model::all(); // or use a ::where()->get();
// And the actual randomisation line
$randRows = $models->shuffle()->slice(0,numberOfRows);
Et voila - happy coding! Vote it up when you see it so it'll rise on the page :)
Laravel 5.4
1) if need one random model:
$object = Model::all()->random();
2) if need many random models:
$object = Model::all()->random($n); //$n - number of elements
//$object - collection
Comment: Calling $collection->random(1) will now return a new collection instance with one item.This method will only return a single object if no arguments are supplied.
Doc ref: https://laravel.com/docs/5.4/collections#method-random