Laravel get unique values from database

Laravel get unique values from database or collection; In this article, we will discuss how to get unique values from the database or collection using Laravel.

Laravel get unique values from database

Using the following methods, you can get unique values from collection or database in laravel apps:

  • Method 1: Using distinct()
  • Method 2: Using groupBy()
  • Method 3: Using Eloquent

Let’s consider a scenario where we have a table named “users” with columns “id”, “name”, “email”, and “age”. Now we want to retrieve unique values from the “age” column.

Method 1: Using distinct()

Laravel’s Query Builder provides the distinct() method to retrieve unique values from a column. Here’s an example:

$ages = DB::table('users')->distinct()->pluck('age');

In the above code, we first select the “age” column from the “users” table using the pluck() method. Then we chain the distinct() method to retrieve only the unique values.

Method 2: Using groupBy()

Another way to retrieve unique values is by using the groupBy() method. Here’s an example:

$ages = DB::table('users')->groupBy('age')->pluck('age');

In this code, we group the records by the “age” column and then select the “age” column using the pluck() method. This will return an array of unique ages.

Method 3: Using Eloquent

If you are using Laravel’s Eloquent ORM, you can use the distinct() method or groupBy() method to retrieve unique values. Here’s an example:

$ages = User::distinct()->pluck('age');

In the above code, we use the User model to select the “age” column and chain the distinct() method to retrieve only the unique values.

$ages = User::groupBy('age')->pluck('age');

In this code, we group the records by the “age” column and then select the “age” column using the pluck() method. This will return an array of unique ages.

Conclusion

Retrieving unique values from a database is a common task in Laravel development. In this article, we discussed three methods to retrieve unique values using Laravel’s Query Builder and Eloquent ORM. By using these methods, you can easily retrieve unique values from any column in your database.

More Tutorials

Leave a Comment