I have 3 tables which are polls, poll_questions and poll_choices. Their relation is polls has many poll_questions and poll_questions has many poll_choices. I am trying to insert but i get an error BadMethodCallException for poll_choices().
Poll Model :
public function poll_questions() {
return $this->hasMany(PollQuestion::class);
}
Poll Question Model :
public function polls() {
return $this->belongsTo(Poll::class, 'poll_id');
}
public function poll_choices() {
return $this->hasMany(PollChoice::class);
}
Poll Choices Model :
public function poll_questions() {
return $this->belongsTo(PollQuestion::class, 'poll_question_id');
}
Here is my controller :
public function store(Request $request) {
$rules = [
'title' => 'required',
'questions' => 'required|poll_questions',
];
$this->validate($request, $rules);
$newPoll = Poll::create(request()->all());
$questions = $request->input('questions');
for ($i = 0; $i < count($questions); $i++) {
$poll_question = new PollQuestion();
$poll_question->input_type = $questions[$i]["input_type"];
$poll_question->question = $questions[$i]["question"];
$newPoll->poll_questions()->save($poll_question);
if ($questions[$i]["input_type"] === '0') {
for ($j = 0; $j < count($questions[$i]["choices"]); $j++) {
$poll_choices = new PollChoice();
$poll_choices->choice = $questions[$i]["choices"][$j];
$newPoll->poll_questions()->poll_choices()->save($poll_choices);
}
}
}
return $this->showOne($newPoll);
}
I get an error in this line : $newPoll->poll_questions()->poll_choices()->save($poll_choices);
Also, i tried : $newPoll->poll_questions->poll_choices()->save($poll_choices);
I can add poll and poll_question perfect. But when i try to add poll choice, it gives an error. I can not access poll_questions' poll_choices method.
How can i fix this problem ?
Laravel 5.4
Full Error Log :
BadMethodCallException Call to undefined method Illuminate\Database\Query\Builder::poll_choices()