Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gouseferoz's avatar

Random method in Eloquent.

Hi Guys,

I am using a random method to fetch the rows in a random manner. But i feel that random is not picking till the end of the table.

    $getPages = Pages::where('author','feroz')->get()->random(10)->pluck('id');

Is that so?

If yes, can you please suggest me how I can go till the last row of the table.

Regards, Feroz.

0 likes
8 replies
Snapey's avatar
Snapey
Best Answer
Level 122

why not use the querybuilder function for this?

$getPages = Pages::where('author','feroz')->inRandomOrder()->pluck('id');
gouseferoz's avatar

@snapey thanks for the workaround and inRandomOrder() looks better than `random()'

However to get only a certain number of random records I used

inRandomOrder()->take(30)

Is this the right way of doing that? or is there any better way?

Please clarify.

Snapey's avatar

yes that would work, but you have to add ->get()

gouseferoz's avatar

@snapey It is working without adding get()

Pages::inRandomOrder()->take(30)->pluck('id');
Snapey's avatar

yep.

certain functions trigger the query. like first(), get(), pluck() etc. I was pointing out that take() is not one of these

so, is it working better? can you select best answer?

gouseferoz's avatar

So should I use like

Pages::inRandomOrder()->get()->take(30)->pluck('id');
``
Snapey's avatar

no. what you had before. But why do you only need ids?

gouseferoz's avatar

I need ids to do something later in the project :)

If the first query shows some errors i will use the later.

Thanks for the help @snapey

Please or to participate in this conversation.