Laravel - Orderby Random using rand() and DB::raw() example

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

Sometimes, we require to get randomly data using laravel query builder. you can use mysql rand() with order by. If you want to get random data using laravel eloquent then we need to use DB::raw(). In bellow lesson you can i use DB::raw().

In this lesson i use DB::raw('RAND()') inside orderBy() and also add limit of 8 number of record, so you can easily implement in your laravel project. so let's try...

return DB::table("posts")

->select("posts.*")

->orderBy(DB::raw('RAND()'))

->take(8)

->get();

Recent Posts

Related Posts