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

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

No comments or questions yet...

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 66 courses (1167 lessons, total 43 h 18 min)
  • 88 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses