Mahdi.Pishguy Mahdi.Pishguy - 3 years ago 273
PHP Question

Laravel select random id from table

i want to select random id from inserted data into table by this code, this code work fine when i dont have deleted row(s) from table, how can i manage or skip deleted row(s) on this part of code:

rand($minId, $maxId)


code:

$minId = DB::table('channel_image_container')->min('id');
$maxId = DB::table('channel_image_container')->max('id');

while (!$c = DB::table('channel_image_container')->find(rand($minId, $maxId))) {
}

echo json_encode([
'path' => 'images/' . $c->file_name,
'content' => $c,
'parent' => DB::table('channel_content_type')->where('id', $c->content_id)->first()
]);


this part of code is best solution?

while (!$c = DB::table('channel_image_container')->find(rand($minId, $maxId))) {
}

Answer Source

I would take advantage of inRandomOrder() (Laravel >= 5.2):

$c = DB::table('channel_image_container')->inRandomOrder()->first();

echo json_encode([
    'path' => 'images/' . $c->file_name,
    'content' => $c,
    'parent' => DB::table('channel_content_type')->where('id', $c->content_id)->first()
]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download