How to get distinct values for non-key column fields in Laravel

0 votes
Hello,

I have a table that can have repeated values for a particular non-key column field. How do I write a SQL query using Query Builder or Eloquent that will fetch rows with distinct values for that column?
Mar 30, 2020 in Laravel by kartik
• 37,520 points
23,820 views

1 answer to this question.

0 votes

Hello @kartik

In eloquent you can use this

$users = User::select('name')->groupBy('name')->get()->toArray() ;

groupBy is actually fetching the distinct values, in fact the groupBy will categorize the same values, so that we can use aggregate functions on them. but in this scenario we have no aggregate functions, we are just selecting the value which will cause the result to have distinct values.

Hope this will help you out!

Thank you!!

answered Mar 30, 2020 by Niroj
• 82,800 points

Related Questions In Laravel

0 votes
1 answer

.How to turn off CSRF protection for a particular route in Laravel?

Hey, We can add that particular URL or ...READ MORE

answered Mar 24, 2020 in Laravel by Niroj
• 82,800 points
4,821 views
+2 votes
2 answers

How to add a new column to existing table of laravel in a migration?

You need do little modification in your ...READ MORE

answered Dec 10, 2020 in Laravel by anonymous
• 82,800 points
127,278 views
0 votes
1 answer

How to set port for php artisan.php serve in Laravel?

Hii @kartik, When we use the php artisan serve ...READ MORE

answered Mar 30, 2020 in Laravel by Niroj
• 82,800 points
19,234