Laravel: htmlspecialchars() expects parameter 1 to be string, with anchor tag text?

Viewed 1012

First time using Laravel and i've downloaded a project. I get this error htmlspecialchars() expects parameter 1 to be string, array given I've found it is due to the following:

@guest
<li class="nav-item"><a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a></li>
@if (Route::has('register'))
    <li class="nav-item"><a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a></li>
@endif

If i remove {{ __('Login') }} and {{ __('Register') }} the error is removed and i can view the page? How do i solve? What could be the reason for this error?

1 Answers

The error is saying that __('Login') is not a string. This means that it likely is an array of translation keys, as __() by default returns a string (the passed parameter) if the translation is not available.

Inside of resources/lang/{lang}, there is a file called login.php:

return [
  'login' => 'Login',
  'register' => 'Register'
];

To access this translation, you need to use the correct syntax:

<li class="nav-item"><a class="nav-link" href="{{ route('login') }}">{{ __('login.login') }}</a></li>
<li class="nav-item"><a class="nav-link" href="{{ route('register') }}">{{ __('login.register') }}</a></li>

The string passed to the __() function should first specify the file, followed by any number of keys (as nested arrays are valid). In both cases, login is the file, followed by the keys login and register.

This structure should be duplicated in all resources/lang/{lang}/login.php files, or the default locale (in most cases en) will be used.

The full documentation can be found here: https://laravel.com/docs/7.x/localization

Related