1

I cannot find the way to display random results from a collection in laravel mysql. My query:

public function getTabletsProducts()
{
    return DB::table('products')
        ->orderBy('created_at')
        ->where('categoryName', 'All Tablets')
        ->where('sellingPrice', '<', 1000)
        ->take(6)
        ->orderByRaw("RAND()")
        ->get();
}

They weird thing is that I believed that using RAND would perform the job, but my results display same values using or not (rand).

any help appreciated.

2

2 Answers 2

0

You should use take(6)->inRandomOreder()->get(). That should do the trick.

Sign up to request clarification or add additional context in comments.

Comments

0

I'm not sure, but I think that's because you take 6 items at first and then order them randomly. So you always get the same or the near result. If I were you I would try this:

public function getTabletsProducts()
{
return DB::table('products')
    ->where('categoryName', 'All Tablets')
    ->where('sellingPrice', '<', 1000)
    ->orderByRaw("RAND()")
    ->orderBy('created_at')
    ->take(6)
    ->get();
 }

1 Comment

and bring the order by created at to the end of the script before take

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.