hoah99
hoah99

Reputation: 21

foreach just return 1 value Laravel

I want to show a test with questions and answers. A question have 4 answers. But I just get 4 answers of a question to all questions. How can I fix it?

   public function xem($id){
    $quests_of_test = QuestofTest::where('id_test', $id)->get();
  
    $ids = $quests_of_test->pluck('id_quest')->all();

    $questions = Question::whereIn('id', $ids)->get();

    foreach($questions as $quest){
        $answers = Answer::where('id_quest', $quest->id)->get();
    }
    
   
    return view('Test::xem', compact('questions', 'answers'));
}

Upvotes: 0

Views: 529

Answers (3)

Ahmad Usmanov
Ahmad Usmanov

Reputation: 50

Just do like this

public function xem($id){

$quests_of_test_ids = QuestofTest::where('id_test', $id)->pluck('id_quest')->toArray();
$questions = Question::query()->whereIn('id', $quests_of_test_ids)->with('answers')->get();

return view('Test::xem', compact('questions'));
}

in view when u iterate $question u can do $question->answer

but before u shoul do

public function answer()
{
     return $this->hasOne(Answer::class, 'id_which_by_related')
     //return $this->hasMany(Answer::class, 'id_which_by_related') in case it has many answers so u should foreach it to iterate collection of answers
}

Becouse your variable in foreach was been overwritten by next iteration u got last iteration data

Work on your code and dont do like that anymore pls) learn about joins and relations

Upvotes: 1

julianstark999
julianstark999

Reputation: 3616

If you define your Relations correctloy you can use Eager Loading to get alle answers with the question.

public function xem($id) {
    $quests_of_test = QuestofTest::where('id_test', $id)->get();
  
    $ids = $quests_of_test->pluck('id_quest')->all();

    $questions = Question::with('answers')->whereIn('id', $ids)->get();
   
    return view('Test::xem', compact('questions'));
}

Upvotes: 0

Mhmd Az
Mhmd Az

Reputation: 82

The reason is variable $answers will be re-assigned for each loop inside foreach.

You may use

$answers = [];
foreach($questions as $quest){
    $answers = array_merge($answers, Answer::where('id_quest', $quest->id)->get());
}

Upvotes: 0

Related Questions