Search code examples
phplaraveleloquentslimtwig-extension

For loop with two database queries in Twig


I'd really love if anyone can help, I'm trying to figure out a way to loop through two queries in Twig. I can create it in PHP but I'm having doing the same thing on Twig. This is how I'd normally do it on PHP:

foreach($items as $item){
   $product_id = $item;
   $products = $app->db->table('products')->where('id', $product_id)->first();
   echo "<li>" . $products->title . "</li>";
}

The above code will work fine but on Twig it will not loop to the next loop, but it will keep on looping the same thing. Kindly help if you know how I can use Twig for loop like I use it above. I'm querying it using Laravel Eloquent in Slim.

This is what I did:

The controller

$products = $app->db->table('products')->where('trash', '0')->first();

The View

{% for item in items %}
      {% set product_id = item.id %}
       <li> {{ products.title }}</li>
{% endfor %} 

It will only show the first row and repeat the samething.


Solution

  • Don't attempt to run queries from a template. Do it in the controller and pass the result to the template.

    Also $items appears to be an array of IDs, so you should be able to load all of the products at once with a where-in condition (instead of multiple queries):

    Controller:

    $products = $app->db->table('products')->whereIn('id', $items)->get();
    
    // pass $products to the template as "products"
    

    Twig template:

    {% for product in products %}
        <li>{{ product.title }}</li>
    {% endfor %}