Consultations nestled in Laravel

Asked

Viewed 100 times

2

I’m starting at Laravel now and I’m having some difficulties when it comes to "consultations".

I’m using the latest version of Laravel which, if I’m not mistaken, is 7.4.

When I worked with pure PHP I did my queries, in specific cases, like this:

$consultaCategoria = "SELECT * FROM categoria";
$objConsutaCategoria = mysqli_query($conexao, $consultaCategoria);
while($arrLinhaCategoria = mysqli_fetch_array($objConsutaCategoria, MYSQLI_ASSOC)){
    
    echo "<h2>{$arrLinhaCategoria['title']}</h2>";
    
    $consultaProduto = "SELECT * FROM produto where categoria_id = {$arrLinhaCategoria['id']}";
    $objConsutaProduto = mysqli_query($conexao, $consultaProduto);
    while($arrLinhaProduto = mysqli_fetch_array($objConsutaProduto, MYSQLI_ASSOC)){
        
        echo "<h2>{$arrLinhaProduto['title']}</h2>";
    
    }

}

But I don’t know how to make this structure in the Aravel.

I thought I’d do it right in the view:

@foreach ($subcategories as $subcategory)

   <h2> {{$subcategory->title}} </h2>

   @foreach ($products as $product)
      @if ($product->subcategory_id == $subcategory->id)
         
           <h2> {{$product->title}} </h2>

      @endif
   @endforeach

@endforeach

Only this way I bring a very large load of products in the consultation. Imagine you have 100 products, I will end up bringing the 100 products in the foreach for each category.

In short, I need to list all the categories together with all your products.

1 answer

1


As I understand it, a product belongs to a subcategory, right? So a subcategory has several products, namely a relation One to Many. This way, you can access the products that belong to your subcategory as follows:

@foreach ($subcategories as $subcategory)
   <h2> {{$subcategory->title}} </h2>
   @foreach ($subcategory->products as $product)
           <h2> {{$product->title}} </h2>
   @endforeach
@endforeach

If the relation is not yet defined, you can define it as the one we found in Docs. In your case, the model Subcategory.php would have:

class Subcategory extends Model
{
    public function products()
    {
        return $this->hasMany('App\Product');
    }
}

Thus calling $subcategory->products return all products belonging to subcategory stored in $subcategory

  • 1

    Luca thank you very much, manage to understand how it works thanks to your reply, and manage to implement in my application. Thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.