I have 2 different tables data has order_id
and I want to sort it in laravel blade foreach.
My Controller:
$questions = Question::where('quiz_id', $quiz->id)->orderBy('order_id', 'asc')->get();
$explanations = Explanations::where('quiz_id', $quiz->id)->orderBy('order_id', 'asc')->get();
My Blade: (I want to sort this 2 foreach by order_id)
@foreach($questions as $question)
<p>{{$question->title}}</p>
@endforeach
@foreach($explanations as $explanation)
<p>{{$explanation->title}}</p>
@endforeach
My Result:
<p>First Question</p> //order_id: 1
<p>Second Question Question</p> //order_id: 3
<p>First Explanation</p> //order_id: 2
<p>SecondExplanation</p> //order_id: 4
Result I Want:
<p>First Question</p> //order_id: 1
<p>First Explanation</p> //order_id: 2
<p>Second Question</p> //order_id: 3
<p>Second Explanation</p> //order_id: 4
CodePudding user response:
in the controller use toArray() and use array merge to merge the two arrays and sort them in the controller
CodePudding user response:
try this if it works:
@for($i = 0; $i <= $questions - 1; $i )
<p>{{$questions[$i]->title}}</p>
<p>{{$explanations[$i]->title}}</p>
@endforeach
or use jsondecode()
to convert questions and explanations to array then:
@for($i = 0; $i <= $questions - 1; $i )
<p>{{$questions[$i]['title']}}</p>
<p>{{$explanations[$i]['title']}}</p>
@endforeach
This would only work if the number of questions and explanations are same.
CodePudding user response:
If in explaination there is question id then You can join the table and u can get esily get what you want.
or May be this thing can work for you.
@foreach($questions as $qKey => $question)
@foreach($explanations as $aKey => $explanation)
@if($qKey == $aKey)
<p>{{$question->title}}</p>
<p>{{$explanation->title}}</p>
@endif
@endforeach
@endforeach