How to display random rows without repetition in laravel?

Member

by ryleigh , in category: PHP Frameworks , a month ago

How to display random rows without repetition in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , a month ago

@ryleigh 

To display random rows without repetition in Laravel, you can use the inRandomOrder() method along with the limit() method.


Here is an example of how you can achieve this:

1
2
3
4
5
6
7
$randomRows = YourModel::inRandomOrder()
    ->limit(5) // Change the limit based on your requirement
    ->get();

foreach($randomRows as $row) {
    // Display the data as needed
}


This code will retrieve 5 random rows from the YourModel table without any repetition. You can adjust the limit() method to retrieve the desired number of random rows.