Home > Back-end >  Laravel Blade simple foreach including $loop->first
Laravel Blade simple foreach including $loop->first

Time:01-09

I have a form where I display four text field inputs. The current app()->getLocale() input is displayed on the left, and the below code is for the remaining 3 locales which are displayed on the right:

@foreach(['ca','en','es','nl'] as $lang)

    @if(app()->getLocale() == $lang) @continue @endif

    <li>
        <a href="#{{ $lang }}" 
    </li>

@endforeach

These are all menu tabs that are hidden, only the first one should be displayed as active, hence:

@if($loop->first) active @endif

The problem however is, that when the current locale is ca, also the $loop->first() will be ca. And this one cannot be the active one, since it will never be displayed on the right side.

I am trying to find an easy fix without too many if else things. Also, the array ['ca','en','es','nl'] will be changed for some data that comes from the config, so there will be more locales later and ca will not always be the first one. So I cannot do checks with @if(app()->getLocale() == 'ca') since that will change in the future as well.

CodePudding user response:

Instead of:

['ca','en','es','nl']

with:

array_diff(['ca','en','es','nl'], [app()->getLocale()])

and remove this:

@if(app()->getLocale() == $lang) @continue @endif

This will remove the item representing the current language from your array.

  • Related