How to retrieve translation strings inside a php code in laravel blade template

1.9k Views Asked by At

I am trying to use the localization retrieval of string inside of php foreach loop code in blade template in laravel 8.

Inside the foreach loop, I am trying to manipulate a value called $item['label'] and equate translate the value of it using the language localization that laravel have.

Here's my current code.

@foreach ($items as $item)
    @php
    $item['label'] = "{{ __($item['label']) }}"
    @endphp
@endforeach

But I get an error of

ParseError syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING)

In the first place, can I use a {{ __ ('string') }} or @lang('string') inside a @php in the first place? If I can't is there any other approach for this one?

Thank you very much!

3

There are 3 best solutions below

0
On BEST ANSWER

while using foreach you cant change its value here try this this will work if $items is array not stdClass

@foreach ($items as $key => $item)
    @php
    $items[$key]['label'] = __($item['label']);
    @endphp
@endforeach
0
On

@php and @endphp is a blade syntax, and it is the same as writing:

<?php ?>

So you could do this:

<?php  
  echo __('profile/username'); 
?>

Or you can write it using a Blade template engine:

@php
   echo __('profile/username'); 
@endphp

To print the items you could do this:

@foreach ($items as $key => $item)         
     {{  __($item) }}
@endforeach

Here an example with data:

@php 
 $items = ['engine_1' => ['label' => 'Google'], 'engine_2' => ['label' => 'Bing']];
@endphp

@foreach ($items as $key => $item)         
     {{  __($item['label']) }}
@endforeach

// The output will be => Google Bing

In order to save the translation of the item, remove the "{{ }}" and use the key in order to detect on which index to apply the changes, like the following:

@foreach ($items as $key => $item)
   @php     
     $items[$key]['label'] =  __($item['label'])
   @endphp
@endforeach

Notice what @Nurbek Boymurodov wrote to you, you need to use the $key, because doing something like this will not override the data within a foreach loop:

@foreach ($items as $key => $item)
    @php
      $item['label'] =  __($item['label']); // Wrong way of overriding data
    @endphp
@endforeach
1
On

Thanks, @Nurbek Boymurodov!

It was your comment that answered my question.

Here's the code right now:

@foreach ($items as $item)
    @php
    $item['label'] = __($item['label']);
    @endphp
//other codes where I used the manipulated $item['label']
@endforeach

by just deleting the {{ }} I've manipulated the value that I want, Thank you!