Home > front end >  Getting weird undefined foreach error in Laravel Blade
Getting weird undefined foreach error in Laravel Blade

Time:10-19

I'm working with Laravel 5.8 and I have this syntax:

@php($counter_foreach = 0)
@foreach($memnames as $mem=>$memname)
@php 
            
@endphp 
@endforeach

Now when I run this, I get syntax error, unexpected 'endforeach' (T_ENDFOREACH) error:

enter image description here

But when I remove @php @endphp, and replace it with html, the error will be gone!

So what's going wrong here?

Is there anything wrong about using @php after @foreach in Laravel Blades?

CodePudding user response:

You actually do not need to make separate php variable for the iterations, so since you have a foreach loop already your logic should be something like this.

@foreach($this as $that) {
   @if ($loop->first)
     // some logic
   @endif

   @if ($loop->last)
    // some logic
   @endif
@endforeach

The $loop variable is available inside the foreach and you check for the iteration number you need inside, I just added some basic uses. Here is some more useful documentation.

CodePudding user response:

Try to add @endphp everytime you add @php like this:

@php($counter_foreach = 0)
@endphp
@foreach($memnames as $mem=>$memname)
@php 
            
@endphp 
@endforeach
  • Related