Laravel retrieving records in a random order

David Carr

Laravel Framework PHP & MySQL Tutorials

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();

 

Fathom Analytics $10 discount on your first invoice using this link

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

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.