Assuming you have defined a belongsToMany relation between Product and `Category. If you already have a Product instance, you can get the related Categories using:
$categories = $product->categories
If you are fetching a Collection of Product instances; you can eager-load the Categories using:
$products = Product::with('categories')
If you just want a distinct list of Categories related to a given Collection of Products
Category::whereHas('products', fn ($builder) => $builder->whereIn('id', $products->pluck('id'))->get();