stefan7
2 months ago
278
5
Laravel

Get unique values of Eloquent relationship

Posted 2 months ago by stefan7

I have a Product and Branch model with m:n relationship. The following query gives me a collection of products, including the branches relationship. What is a good way to get a list of unique branches (used as a filter in a select list on frontend) with the following query?

  $products = Product::whereHas('categories', function($query){
                 $query->where('id', 2); 
             })
            ->with(['branches'])
            ->orderBy('created_at', 'desc')
            ->get();

Please sign in or create an account to participate in this conversation.