Используйте where()
, прежде чем get()
улучшит производительность.
И вы можете использовать pluck('brand_id')
на $products
коллекции, чтобы получить brand_ids
:
$product_sub_categories = ProductsSubCategory::where('product_sub_category_slug', $slug)->first();
$products = Products::where('subcategory_id', $product_sub_categories->id)->get();
$brands = Brand::whereIn('id', $products->pluck('brand_id')->all())->get();