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.

s_h
  • 1,476
  • 2
  • 27
  • 61

2 Answers2

0

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

GabMic
  • 1,422
  • 1
  • 20
  • 37
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();
 }
Tohid Dadashnezhad
  • 1,808
  • 1
  • 17
  • 27