在刀片LARAVEL中排序答案

在刀片LARAVEL中排序答案

问题描述:

I have this code, and I want to sort them by order, I have the order column in database which always takes 1, 2, 3, 4 and I want the answers to be in that order how can I do this on laravel blade .

<div class="form-group" id="group-form-id">
    <label id="correct_answer" style="color: #00a65a;">
        @lang('test-results.correct_answer'):

        <div style="line-height: 8px; padding-top: 5px;">
            <?php $i=1; ?>
            @foreach($question->answers as $answer)
                @if($answer->order)
                    <span id="test_span">
                        <br>
                        <em style="padding-right: 10px; color: #999;">
                            {{ $i }}.
                        </em>
                        {!! $answer->text !!}
                    </span>
                    <hr style="width: 500%;border-top: 1px solid rgba(238, 238, 238, 0.37);">
                @endif
                <?php $i++; ?>
            @endforeach
        </div>
    </l

我有这个代码,我想按顺序对它们进行排序,我有 order code >数据库中的列总是需要 1,2,3,4 code>,我希望答案按顺序排列,如何在laravel blade上执行此操作。 p>

 &lt; div class =“form-group”id =“group-form-id”&gt; 
&lt; label id =“correct_answer”style =“color:#00a65a;”&gt; 
 @lang  ('test-results.correct_answer'):
 
&lt; div style =“line-height:8px; padding-top:5px;”&gt; 
&lt;?php $ i = 1;  ?&gt; 
 @foreach($ question-&gt;答案为$ answer)
 @if($ answer-&gt; order)
&lt; span id =“test_span”&gt; 
&lt; br&gt; 
  &lt; em style =“padding-right:10px; color:#999;”&gt; 
 {{$ i}}。
&lt; / em&gt; 
 {!!  $ answer-&gt; text !!} 
&lt; / span&gt; 
&lt; hr style =“width:500%; border-top:1px solid rgba(238,238,238,0.37);”&gt; \  n @endif 
&lt;?php $ i ++;  ?&gt; 
 @endforeach 
&lt; / div&gt; 
&lt; / l 
  code>  pre> 
  div>

I think you can try this :

<div class="form-group" id="group-form-id">
                    <label id="correct_answer" style="color: #00a65a;">
                        @lang('test-results.correct_answer'):
                        <div style="line-height: 8px; padding-top: 5px;">
                            <?php $i=1; ?>
                        @foreach($question->answers->sortBy('order') as $answer)
                                @if($answer->order)

                                <span id="test_span"><br><em style="padding-right: 10px; color: #999;">{{ $i }}.</em>{!! $answer->text !!}</span>
                            <hr style="width: 500%;border-top: 1px solid rgba(238, 238, 238, 0.37);">
                            @endif
                            <?php $i++; ?>
                        @endforeach
                        </div>

Hope this work for you !!!

You can sort the answers collection:

$question->answers->sortBy('order')

Check Laravel Collections

In the controller when you return the questions you can use query builders orderBy(order). See this documentation: Laravel Query Builder - Order By