Hi, my name is David Carr and I'm a PHP Developer.

Blog Archives Categories Authors About Me Open Source Books Contact Me

Sponsor Me

Help support the blog so that I can continue creating new content!

My Latest Book

Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Laravel retrieving records in a random order

Laravel Framework | PHP & MySQL | Tutorials

David Carr

Laravel retrieving records in a random order

Retrieving records in a random order is simple with MySQL using the RAND() function but it's not very random ironically especially when dealing with a few records. a better way is to make use of inRandomOrder attribute that Laravel provides for models.

In this example return 3 records in a random order.

$rand = Post::inRandomOrder()->take(3)->get();


Copyright © 2009 - 2022 David Carr. All code MIT license. All rights reserved.