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

By Hardik Savani | May 4, 2016 | | 55474 Viewer | Category : Laravel


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 example you can i use DB::raw().

In this example 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();



Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.


We are Recommending you: