Today now here i will discus on Orderby Random using rand() and DB::raw() in Laravel. Sometimes, we need to get randomly data by using laravel query builder. We can use mysql rand() with order by. If we want to get the random data by using laravel eloquent then we need to use DB::raw().
Now In the bellow example you can use DB::raw().
So now in this example i will use DB::raw(‘RAND()’) inside orderBy() and also need to add limit of 8 number of record, so we can easily implement in our laravel project.
So let’s try this:
Example:
return DB::table("posts")
->select("posts.*")
->orderBy(DB::raw('RAND()'))
->take(8)
->get();
Read Also : How to convert Object into Array in PHP?
Thanks for read. I hope it help you. For more you can follow us on facebook.