DolDurma
DolDurma

Reputation: 17331

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))) {
}

Upvotes: 2

Views: 2531

Answers (2)

GabMic
GabMic

Reputation: 1482

You will need to take it like so:

$c = DB::table('channel_image_container')->take(1)->inRandomOrder()->get();

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

Upvotes: 2

aaron0207
aaron0207

Reputation: 2333

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()
]);

Upvotes: 4

Related Questions