I am coming from a Rails background where we can create has_many_through pretty easily with the right references.
My models in this project: Deal <=> DealsFaqs <=> Faqs
In the Deals model I have:
public function faqs(){
return $this->hasManyThrough('App\Faq', 'App\DealsFaqs');
}
DealsFaqs has:
public function deals()
{
return $this->belongsTo('App\Deal');
}
public function faqs()
{
return $this->belongsTo('App\Faq');
}
and my Faq model has:
public function deals(){
return $this->hasManyThrough('App\Deal', 'App\DealsFaqs');
}
A deal needs to be able to be associated with N faqs.
So I created a table for DealsFaqs that has a deal_id and a faq_id fields.
I am easily able to list the FAQ's on the Deal form page, but that isn't tied to the DealsFaqs.
How do I output the faqs but submit them through the form in a way that I can then check the relationship in the controller on submission?
--- EDIT BASED ON REQUEST FOR MORE CODE AND DETAIL:
Ultimately there will be roughly 20-30 faqs. And a growing number of deals. As the admin creates each deal they need to select which FAQ's are relevant to the deal. Some will be relevant and others won't be. Then those FAQ's will be output to the page.
I assumed I needed a hasManyThrough because I can't just put a single faq_id field on the Deal as it needs many and the same on the FAQ. FAQ's belong to many deals.
My DealCreate Method in the Controller:
///////////////////
// ASSOCIATE FAQ's TO DEALS
///////////////////
if($request->faqs){
foreach($request->faqs as $key => $faq){
// Create new DealsFaqs
$entry = new \App\DealsFaqs;
// Populate it
$entry->faq_id = $faq['id'];
$entry->deal_id = $deal->id;
$entry->save(); // Save the DealsFaqs
}
}
Then my current form section to relate FAQ's to deals:
<?php $a=0; foreach($faqs as $faq): ?>
<div class="col-sm-12">
<label>
<input type="radio" name="faqs[{{ $a }}][id]" value="{{ $faq->id }}">
{{ $faq->name }}
</label>
</div>
<?php $a++; endforeach; ?>
When I select 1 or all of them a new relationship is created on the deals_faqs table I created. But then for obvious reasons (I don't know how to solve) But the radios don't know to stay checked, and I don't know how to access/update in the controller. ALSO is this the right way to do this or am I wrong with the relationships?