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

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

By Hardik Savani May 4, 2016 Category : LaravelPlayUnmuteLoaded: 1.17%Fullscreen[![VDO.AI](https://a.vdo.ai/core/assets/img/logo.svg)](https://vdo.ai/?utm_medium=video\&utm_term=itsolutionstuff.com\&utm_source=vdoai_logo)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...

Read Also: [Order by using multiple columns and manually array field in Laravel?](https://www.itsolutionstuff.com/post/order-by-using-multiple-columns-and-manually-array-field-in-laravelexample.html)

```php
return DB::table("posts")
->select("posts.*")
->orderBy(DB::raw('RAND()'))
->take(8)
->get();
// select `posts`.* from `posts` order by RAND() asc limit 8
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://learnphp.gitbook.io/learnphp/laravel-advanced/laravel-orderby-random-using-rand-and-db-raw-example-ok.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
