Home > database >  Why $variable not working properly in Lavarel Blade?
Why $variable not working properly in Lavarel Blade?

Time:08-22

I just encounter a situation where I need to display index for each row of table, For this I created a variable ($number) in blade view file and set it to 0. For row of my table I created a component and pass my data to it, incrementing index ($number) for each row. But actually it is incrementing twice.

My blade :

@if($staff_profile->passport_expiry!=null&&$staff_profile->passport_expiry<$exp_date)
   <x-staf_expiry_row :id=" $staff_profile->id" :name="$staff_profile->name" type="Passport" :date="$staff_profile->passport_expiry" :number="$number  "/>
@endif

and the result is:

before

But it works fine after a simple change :

@if($staff_profile->passport_expiry!=null&&$staff_profile->passport_expiry<$exp_date)
   <x-staf_expiry_row :id=" $staff_profile->id" :name="$staff_profile->name" type="Passport" :date="$staff_profile->passport_expiry" :number="$number  "/>
   @php($number  )
@endif

after

Why $number increment twice and what's the proper way of doing it?

Thanks for your time!

CodePudding user response:

Use the $loop variable from @foreach, so, let's say you have a @foreach, you should have this blade:

@foreach ($staff_profiles as $staff_profile)
    @if($staff_profile->passport_expiry != null && $staff_profile->passport_expiry < $exp_date)
       <x-staf_expiry_row :id="$staff_profile->id" :name="$staff_profile->name" type="Passport" :date="$staff_profile->passport_expiry" :number="$loop->index"/>
    @endif
@endforeach

CodePudding user response:

I think, in your case, the increment is handled by JS and not by your blade

Echo the variable with {{ }}

@if($staff_profile->passport_expiry!=null&&$staff_profile->passport_expiry<$exp_date)
   <x-staf_expiry_row :id=" $staff_profile->id" :name="$staff_profile->name" type="Passport" :date="$staff_profile->passport_expiry"
      :number="{{$number  }}"/>
@endif

Here a more in depth explanation

  • Related