skip to Main Content

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

3

Answers


  1. in the controller use toArray() and use array merge to merge the two arrays and sort them in the controller

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. If in the explanation there is a question id then You can join the table and u can get easily get what you want.

    or Maybe 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search