php

How to set value in for-loop in Laravel blade

Problem

<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 looks like the variable can`t be read.
How to set the value in the for-loop inside the blade?

Solution

So what you need to do is to have this {{ $last = date('Y')-120 }} in first part. With {{ $var }} You are printing the value but you need to assign the value. So assign like this :

<pre class="wp-block-preformatted"><?php $last= date('Y')-120; ?></pre>

The same thing goes for the for a loop too. Just compare the value. Do not put it in blade syntax. You shouldn’t mix the two.

<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>

About the author

laravelrecipies