Falco
Falco

Reputation: 87

Cross data in the same array with Twig

Sorry for the title, I was not inspired. I send (with Slim 3) to Twig an array with 'article' and 'categories'. In 'article', I have a article.cat.id and in 'categories' I have an 'id'. I want just to get the category name by article.cat.id. For the moment, I make a double loop but I assume that's a bad way to do this. Any idea to do this in a better way? Thanks

{% for article in articles %}
    <tr>
        <td>{{ article.title }}</td>
        <td>
            {% for category in categories %}
                {% if category.id == article.cat_id %}
                    {{ category.name }}
                {% endif %}
            {% endfor %}  
        </td>
        <td>{{ article.author }}</td>
    </tr>
{% endfor %}   

Upvotes: 0

Views: 52

Answers (2)

Falco
Falco

Reputation: 87

I found the solution. My array must have my category id as key. To do that with eloquent is:

Category::all()->keyBy('cat_id');

and now I can use:

{{ categories[article.cat_id].name }}

Upvotes: 0

Titi
Titi

Reputation: 1153

You should be able to do

{{ categories[article.cat_id].name }}

(unless the array index is different to the category id attribute)

Upvotes: 2

Related Questions