Skip to main content
Tutorial Free

Laravel Many-to-Many: Get Unique Values with Collections Pluck

August 05, 2023
2 min read

Let me show you a chain of Collection methods to get the colors of products for the dropdown. Imagine you have an e-shop, and you want to list the products of a category, also listing all different colors of those products, for a filter dropdown/checkbox. How to do it?

Imagine this DB schema:

And your goal is to show the page /categories/1 with two elements:

  • List of products of that category
  • List of all possible unique colors for those products as a checkbox for filtering

Here's the code with the solution:

CategoryController.php:

use App\Models\Category;
 
public function show(Category $category) {
$colors = $category->products()
->with('colors')
->get()
->pluck('colors')
->flatten()
->pluck('name', 'id');
 
return view('categories.show', compact('category', 'colors'));
}

As a result, the $colors Collection should look something like this:

Illuminate\Support\Collection {#2173
all: [
9 => "blue",
10 => "silver",
4 => "navy",
14 => "aqua",
15 => "white",
6 => "purple",
7 => "teal",
1 => "black",
],
}

The key part for the unique colors is pluck() method of Collections. If there are repeating colors, it will take only one of them, which is exactly what we need.

Quoting the docs: "If duplicate keys exist, the last matching element will be inserted into the plucked collection:"

If you want to find more real-life examples of such Collection usage, I have a separate course: Laravel Collections Chains: 15 Real Examples

Enjoyed This Tutorial?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Comments & Discussion

No comments yet…

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.