Fan Fan - 5 months ago 39
PHP Question

How to set value in for-loop on laravel blade

<select id="year" name="year" class="form-control ">
{{ $last= date('Y')-120 }}
{{ $now = date('Y') }}

@for ($i ={{ $now }}; $i <= {{ $last }}; $i--)
<option value="{{ $i }}">{{ $i }}</option>
@endfor
</select>


And I got the error message
Parse error: syntax error, unexpected '<'



It look like the variable can`t read.


How to set the value in the for-loop?

Answer

Basically {{ $last= date('Y')-120 }} in this part you are showing the value but you need to assign the value. So assign like this :

<?php $last= date('Y')-120; ?>

Same thing goes for the for loop too.Just compare the value. Do not put it in blade syntax.

<select id="year" name="year" class="form-control ">
    <?php $last= date('Y')-120; ?>
    <?php $now = date('Y'); ?>

    @for ($i = $now; $i <= $last; $i--)
        <option value="{{ $i }}">{{ $i }}</option>
    @endfor
</select>