How create nested relationship over three models

Posted 1 year ago by abombelli


I'm completely new to Laravel and have the following situation:

I have the following Models:

  • Treatments; belongsToMany Products, belongsTo User
  • Products; belongsToMany Treatments, hasManyPrescriptions
  • Prescriptions; ??
  • Users; hasMany Treatments

Treatments can have many Products. Each associated Product to a Treatment can have a unique Prescription.

The tables are:

  • Users (id, name)
  • Treatments (id, name, user_id)
  • Products (id, name)
  • Product_Treatment (product_id, treatment_id)
  • Prescriptions (id, amount, product_id, treatment_id, user_id)

I manage to create the correct relations from products to each treatment. What I cannot figure out is how to relate the prescription to the product in the corresponding treatment. A product can belong to many treatments. If I use a normal pivot table for products_prescription, then this relation applies to all treatments. This should not be the case.

How should I setup the relationship, so I'm able to use this in blade? @foreach ($treatment->products as $product) {{ $product->name }} {{ $product->prescription->amount }} @endforeach

Thanks a lot for any hint or help. Aldo

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up


Reply to

Use Markdown with GitHub-flavored code blocks.