panthro
panthro

Reputation: 24061

Pluck not working as expected in laravel

Following on from my previous question, I need to get an array of a list of random ids from a model, I do:

User::all('id')->random(2)->pluck('id')->toArray()

The above works as expected, plucking 2 ids and putting them in an array:

array:2 [
  0 => 63
  1 => 270
]

When I switch it to just one random user though:

User::all('id')->random(1)->pluck('id')->toArray()

The entire table is returned.

array:200 [
  0 => 63
  1 => 270
  2 => 190
  ...
]

My plan is to use the following to get between 1 and 10 users:

 User::all('id')->random(rand(1,10))->pluck('id')->toArray()

But how can I make this work when only 1 random user is selected, why is the entire table being returned?

Upvotes: 0

Views: 1819

Answers (2)

Elie Faës
Elie Faës

Reputation: 3315

You can use your database to randomize your users, and take full advantage of the query builder and its take method.

User::inRandomOrder()
    ->take(rand(1,10))
    ->pluck('id')
    ->toArray();

inRandomOrder was added in Laravel 5.2+, so if you have less, you can do orderBy(DB::raw('RAND()')) for MySQL (see this post to learn more Laravel - Eloquent or Fluent random row)

Upvotes: 1

Alex Harris
Alex Harris

Reputation: 6392

random(1) will not return a collection, while random(2) and above will. You can first get the query and then handle the results differently dependent on whether or not the result was a collection.

Upvotes: 1

Related Questions