onlinecode

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

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

In this post we will give you information about Laravel – Orderby Random using rand() and DB::raw() example. Hear we will give you detail about Laravel – Orderby Random using rand() and DB::raw() exampleAnd how to use it also give you demo for it if it is necessary.

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…

Also see:Order by using multiple columns and manually array field in Laravel?

return DB::table("posts")

->select("posts.*")

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

->take(8)

->get();

Hope this code and post will helped you for implement Laravel – Orderby Random using rand() and DB::raw() example. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Exit mobile version