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
Now I can insert the values into the pivot table:
$treatment->products()->updateExistingPivot($product->id, [ 'consumption_interval' => request('consumption_interval'), 'units_per_interval' => request('units_per_interval') ]);
Where I'm still stuck, is accessing the values in the view.
The pivot attributes appear fine in the "show" view {{ $product->pivot->units_per_interval }}, but not when editing the attributes. Then the array is missing the pivot relationship.
Any idea what I'm missing?
@foreach ($treatment->products as $product)
$product->pivot->units_per_interval
@endforeach
Then for the edit view I have the following function in the TreatmentsController, where I pass the treatment and product id in the route Route::get('/treatments/{treatment}/prescription/{product}/edit', 'TreatmentsController@edit_prescription'):
public function edit_prescription(Treatment $treatment, Product $product) {
return view('prescriptions.edit', compact('product', 'treatment') );
}
But somehow I do not get the attribute in the edit view via $product->pivot->units_per_interval
Yes. The only difference is, in show I access the pivot over the foreach loop and in the edit view I just pass the $product and $treatment object. And both are missing the relationship.
class Treatment extends Model
{
protected $fillable = ['name'];
public function user() {
return $this->belongsTo(User::class);
}
public function products() {
return $this->belongsToMany(Product::class)->withPivot('consumption_interval', 'units_per_interval');
}
}
Ok, with this I get the treatment with a collections of two associated products.
But in the single edit view I need to additionally filter by product_id.
Do I need to chain where clauses?