0

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?

Community
  • 1
  • 1
panthro
  • 22,779
  • 66
  • 183
  • 324

2 Answers2

1

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.

Alex Harris
  • 6,172
  • 2
  • 32
  • 57
1

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)

Community
  • 1
  • 1
Elie Faës
  • 3,215
  • 1
  • 25
  • 41