0
votes

I have two tables:

Products:

  1. id
  2. name
  3. category_id
  4. Description

Categories:

  1. id
  2. name

How can I display (foreach) all products in a certain category ?

Product Model :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name', 'category_id', 'description',];

    public function category()
    {
        return $this->belongsTo(Category::class);
    }

}

Category Model :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['name',];

    public function products()
    {
        return $this->hasMany('App\Product','category_id');
    }

}

CategoryController :

public function show($id)
    {
        //
        $categories = Product::where('category_id', '=', $id)->get();
        
        return view ('categories.show',compact('categories'));
    }

Show.blade.php :

@foreach ($categories as $product)
             
{{$product->category_id}}
            
@endforeach

{{ $product->category->name }}
3
Using eloquent relationships as you show in your model, you just need to eager loading your category as $category = Category::with('products')->find($category_id); After that, your products will be a collection under $category->products(); - Farid
I get it, I just don't know how to do that - Cristian Ilisei

3 Answers

0
votes

In your Show.blade.php file add this code:

@if($categories)
    @foreach($categories AS $category)
         <div class="">
             {{ $category->category_id.': '.$category->name }}
         </div>
         @if($category->products)
             @foreach($category->products AS $product)
                 <div classs="">
                     {{ $product->id.': '.$product->name }}
                 </div>
                 <div classs="">
                     {{ $product->Description }}
                 </div>
             @endforeach
         @endif
    @endforeach
@endif
0
votes

As far as I understand, In controller, add this,

$categories = Product::with('category')->where('category_id', '=', $id)->get();

Then in your blade, you can access $categories inside foreachloop as $categories->category->name

0
votes

You are in categoryController and you are getting one object - one category by id instead of collection. So you won't have categories in blade file. What you are doing here is getting collection of products. You should reverse your query by doing

public function show($id)
{
    $category = Category::with(['products'])->find($id);
    
    return view ('categories.show', compact('category'));
}

and in blade file

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

{{ $category->name }}