Laravel - Eloquent or Fluent random row
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().
how get random row laravel-5
Update for Laravel 5.4
New randomsorting in Laravel 5.4->inRandomOrder()->first()
Laravel how to get data random row use Postgres SQL?
Eloquent has inRandomOrder()
method.
$recomment_product = Product::where('name', $product->name)
->where('gender', $product->gender)
->where('client_target', $product->client_target)
->inRandomOrder()
->take(3)
->get();
Laravel 5 - how to get a random row from first 30 records in eloquent?
Use get()
before count()
to run the query before count:
$cnt = Record::popular($d)->get()->count();
Laravel eloquent random query
You should have been using orderByRaw
.
But there is a better solution, you can add this macro:
use Illuminate\Database\Query\Builder;
Builder::macro('orderByRandom', function () {
$randomFunctions = [
'mysql' => 'RAND()',
'pgsql' => 'RANDOM()',
'sqlite' => 'RANDOM()',
'sqlsrv' => 'NEWID()',
];
$driver = $this->getConnection()->getDriverName();
return $this->orderByRaw($randomFunctions[$driver]);
});
So you can do: $query->orderByRandom()->take($limit)->get();
Laravel 5.4 Eloquent get x random records from collection where property is null
Why not just add your conditions to a sql-query:
$regions = Region::with('neighbors')
->join('cards', 'cards.id', '=', 'regions.risk_card_id')
->whereNotNull('user_id')
->inRandomOrder()
->limit($regionsPerUser)
->get();
If you already have a collection then you can do something like:
$regions = $regions
->filter(function ($value) {
return !is_null($value['user_id']);
})
->random($regionsPerUser);
How to get random row from the last 5 row?
The Builder
class doesn't have a random()
method, but a Collection
does. Also, oldest()
doesn't take an integer as it's argument, it's looking for a column
to use (uses created_at
as a default).
Use the following query instead:
$posts = Post::inRandomOrder()->limit(5)->get();
Note: Don't use ->first()
if you want multiple rows; ->first()
returns the first row from the database, ->get()
returns rows in a Collection
.
Edit: Misread the question. See the query below:
$randomPost = Post::oldest()->limit(5)->get()->random();
Use the initial Post::oldest()->limit(5)->get()
to get 5 Posts
ordered by created_at
, then use Collection
logic to return a single entry via random()
.
Related Topics
Import CSV File Directly into MySQL
Is There Any Particular Difference Between Intval and Casting to Int - '(Int) X'
Interpolation (Double Quoted String) of Associative Arrays in PHP
Group Array by Subarray Values
MySQL_Fetch_Array, MySQL_Fetch_Assoc, MySQL_Fetch_Object
How to Detect Strings Like Putjbtghguhjjjanika
Localhost Vs. 127.0.0.1 in MySQL_Connect()
PHP Regex: How to Match \R and \N Without Using [\R\N]
How to Add Variation Stock Status to Woocommerce Product Variation Dropdown
Using Default Arguments in a Function
Serializing and Submitting a Form With Jquery and PHP
Redirecting to Previous Page After Login - PHP
Parentheses Altering Semantics of Function Call Result
How to Use a String as an Array Index Path to Retrieve a Value
Error Logging, in a Smooth Way
In PHP With Pdo, How to Check the Final SQL Parametrized Query