P
P
Prodion2021-04-02 15:35:16
Laravel
Prodion, 2021-04-02 15:35:16

Is it possible to rebuild the collection?

There is a Category model and a Product model. There is a many-to-many relationship between these models. On the category page, we get all the products of this category and, for each product, all of its categories.

Example.

$category->type
$category->name

@foreach ($category->products as $product)
    $product->name

    @foreach ($product->categories as $category)
        $category->type
        $category->name
    @endforeach
@endforeach


At the output we get.

Manufacturer
Alize

    Alize Lana Gold

       Manufacturer
       Alize
       Country
       Turkey
       Fiber
       Acrylic


Each category has its own type. For example: Country, Manufacturer or Fiber. Category of country, manufacturer or composition. There is always one Country and Manufacturer for a product, but there can be many Fibers.

Is it possible to somehow rebuild (I don’t know how to say it right) the collection so that the product is returned with all the categories to which it belongs?

That is, to be able to do so.

$category->type
$category->name

@foreach ($category->products as $product)
    $product->country // категория
    $product->manufacturer // категория
    $product->name

    @foreach ($product->fibers  as $fiber) // категория
        $fiber->name
    @endforeach
@endforeach


We explicitly write Country, Manufacturer and only iterate over Fiber in the array, since a product can have many categories of this type.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question