2

When trying to get a random user id in a factory, it always returns null despite the DB containing 50 users (created via the User factory).

'user_id' => User::all()->random()->id

I tried to display the retrieved resource doing this:

dd(User::all()->random())

and the result was quite consistent with what expected

App\User^ {#num
  #fillable: array:9 []
  ...
  #attributes: array:14 [
    "id" => 25
  ...
  ]
}

but this other method:

dd( User::all()->random()->id )

always returns null.

Kenny Horna
  • 13,485
  • 4
  • 44
  • 71
Washery
  • 1,037
  • 1
  • 12
  • 23

1 Answers1

1

Keep in mind that using that method you are loading all the records in memory, then selecting one randomly to get your random object.

You could improve this querying one record in random order directly from the database:

$randomUser = User::inRandomOrder()->first();
Kenny Horna
  • 13,485
  • 4
  • 44
  • 71
  • Tried to assign the random user to a variable and then extracting the ID but it does not work. $randomUser = User::inRandomOrder()->first(); echo dd($randomUser->id); – Washery Oct 07 '19 at 09:32
  • 1
    Check your model. Maybe you have the `id` field included in your `$hidden` config. [Check this](https://laravel.com/docs/5.8/eloquent-serialization#hiding-attributes-from-json) for more info. – Kenny Horna Oct 07 '19 at 14:25
  • Okay I found the problem, I am using https://laracasts.com/discuss/channels/laravel/encrypt-and-decrypt-help-code-example to encrypt the user email but apparently the *Encryptable* trait stops the whole model from working – Washery Oct 07 '19 at 18:15
  • I don't understand your question is different than your actual problem. – Vipertecpro Nov 21 '19 at 07:50