Orderby Random using rand() and DB::raw() in Laravel

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

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.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →