Jesus Cova
Jesus Cova

Reputation: 33

ManyToMany Laravel Relationship

I have my model products:

class Product extends Model
{
  protected $table = 'products';

  protected $primaryKey = 'id_product';

  protected $fillable = [
    'id_category', 'title', 'credit', 'created_at', 'updated_at',
  ];

  public function categories()
  {
    return $this->belongsToMany('App\Category', 'products_categories', 'id_product', 'id_category');
  }
}

I have my category model:

class Category extends Model
{
   protected $table = 'categories';

   protected $primaryKey = 'id_category';

   protected $fillable = [
     'category', 'created_at', 'updated_at',
   ];

   public function products()
   {
       return $this->belongsToMany('App\Product', 'products_categories', 'id_product', 'id_category');
   }
}

I have my table products_categories

I want to list the products that belog to a category so I do this:

$products = Product::with('categories')->get();

foreach ($products as $product) {
  $products->title;
}

But it does not work, I want to know... how can I list?

I have tried all.. and it says Property [title] does not exist on this collection instance.

Thanks

Upvotes: 1

Views: 84

Answers (1)

jackel414
jackel414

Reputation: 1686

The error you're seeing is likely due to a typo. It should be:

foreach ($products as $product) {
  $product->title;
}

Other than that, the rest of your code looks good. Fixing the typo should allow you to access each products' categories via:

foreach ($products as $product) {
    foreach ($product->categories as $category) {
        $category->name // or other attribute
    }
}

Upvotes: 2

Related Questions