How to get the random value form a specific column in laravel ?

Created at 19-Jul-2023 , By samar

To retrieve a random value from a specific column in Laravel, you can use the inRandomOrder() method along with the pluck() method.

$username = App\Models\User::inRandomOrder()->pluck('name')->first();
echo $username;

In above code snippet, User::inRandomOrder() retrieves all rows from the users table in a random order. The pluck('name') method selects only the name column from the resulting collection. Finally, first() retrieves the first value from the collection, which is the random name.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.