Home > Software design >  laravel - append index to a variable in blade
laravel - append index to a variable in blade

Time:07-19

I have multiple columns which is saved with a suffix ended with the index of 1-12, such as savings_date_mth_1 until savings_date_mth_12. As of now, I would like to display this value on blade using for loop, but it cannot read the name of the column when I name it such as below.

@for ($i = 1; $i <= $savings->months_diff; $i  )
<div >
    <div >
        {{ $savings->savings_date_mth_.$i }}
        {{ \Carbon\Carbon::parse($savings->savings_date_mth_.$i)->format('M') }} Savings
    </div>
    <div>
        Cost Item: 100
    </div>
</div>
@endfor

I have tried using {$i} as well but it's not showing the value of the column still. Please enlighten me on this particular issue and what is the best practice for this.

CodePudding user response:

You need to use savings_date_mth as a String, and interpolate or concatenate $i to it.

In PHP, you can use a String to access a property of an Object like this:

$string = 'something';
$object = (object)['something' => 'another'];
{{ $object->{$string} }} // 'another'

But in your case, you're constructing the String from a variable as well:

$i = 1;
$j = 2;
$savings = (object)['savings_date_mth_1' => 100, 'savings_date_mth_2' => 200]);
{{ $savings->{"savings_date_mth_{$i}"} }} // 100
{{ $savings->{"savings_date_mth_{$j}"} }} // 200

So in the end, your code would look like:

@for ($i = 1; $i <= $savings->months_diff; $i  )
<div >
    <div >
        {{ $savings->{"savings_date_mth_{$i}"} }}
        {{ \Carbon\Carbon::parse($savings->{"savings_date_mth_{$i}"})->format('M') }} Savings
    </div>
    <div>
        Cost Item: 100
    </div>
</div>
@endfor

Alternatively, via concatenation:

{{ $savings->{'savings_date_mth_' . $i} }}
{{ \Carbon\Carbon::parse($savings->{'savings_date_mth_' . $i})->format('M') }} Savings

Whichever you prefer, or is consistent with other usage in your project, if any.

  • Related