s_h s_h - 3 years ago 163
MySQL Question

Laravel Php take random results from mysql query

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download