Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel You requested 1 items, but there are only 0 items available

Tags:

php

laravel

I am getting row's column randomly to seed database, using eloquent :

$physician = SelectOption::where('select_option_group_id', 1)->pluck('name')->random();

it works if data exists in select_options table. But if it does not exists, it gives an error :

You requested 1 items, but there are only 0 items available.

I want to leave it empty, if it's empty.

like image 775
Nevermore Avatar asked Oct 19 '17 08:10

Nevermore


2 Answers

Check if collection is not empty prior doing random():

$collection = SelectOption::where('select_option_group_id', 1)->pluck('name');
if (!$collection->isEmpty()) {
    $physician = $collection->random();
} else {
    ...
}
like image 152
Marcin Orlowski Avatar answered Nov 05 '22 15:11

Marcin Orlowski


Use inRandomOrder() instead:

$physician = SelectOption::where('select_option_group_id', 1)->inRandomOrder()->first();
$name = is_null($physician) ? 'No data available' : $physician->name;
like image 3
Alexey Mezenin Avatar answered Nov 05 '22 13:11

Alexey Mezenin