dijkr / Copia

Laravel-project with CMS
0 stars 0 forks source link

Get data from JSON with Antlers #15

Closed dijkr closed 1 year ago

dijkr commented 1 year ago

With Blade it was possbile to parse data from a JSON. I need to iterate over the products from a subcategories and also display the name of the subcategory.

Controller:

 $products = Product::whereHas('category', function ($query) use ($categorySlug) {
            $query->where('slug', $categorySlug); })->get();
        $groupedProducts = $products->groupBy('Subcategory')

This is the result (JSON) name of the resulting key: "{"id":1,"name":"Nederland","created_at":null,"updated_at":null}"

With Blade this works:

            @php
                // The resulting key of the array = JSON
                $subcategory = json_decode($groupedProduct, true);
            @endphp

With Antlers its not working. And unknown yet how to solve this problem.

dijkr commented 1 year ago

Controller:

 $groupedProducts = $products->groupBy('Subcategory')->mapWithKeys(function ($products, $key) {
              $subcategory = json_decode($key, true);
              $name = $subcategory['name'];
              return [$name => $products];
          });

Result name of the resulting key: "Nederland"

Basically it fetched the name value from the subcategory.

dijkr commented 1 year ago

{{ key }} is used to just display the name of the key. The key is renamed to the subcategory from the controller. See the post above this one. Then{{ value }} is used to access every array (every product) nested within the subcategories.

        {{ foreach:groupedProducts }}
            <div class="grid-pd-cat-1">
                {{# SHOW THE SUBCATEGORY #}}
                <div class="grid-item-products-1">
                    <div class="cat">
                        <h4> {{ key }} </h4>
                    </div>
                </div>

                {{# SHOW THE SUBCATEGORY ITS PRODUCTS #}}
                {{ value }}
                    <a href="/product/{{ slug }}">
                        <div class="grid-item-products-1">
                            <div class="top">
                                <img src="/images/{{ Image }}">
                                € {{ Price format_number="2" }}
                            </div>
                            <div class="bottom">
                                {{ Title }}
                                {{ Shortdescription }}
                            </div>
                        </div>
                    </a>
                {{ /value }}
            </div>
        {{ /foreach:groupedProducts }}