epowah epowah - 25 days ago 6
PHP Question

function trans doesn't work in Laravel

I'm trying to make language chooser in laravel with simple text changing, I have two php files

greetings
in language folders, one in english, one in german.

This code is in
de
folder:

return array(
'hello' => 'Hallo'
);


and this is in the
en
folder

return array(
'hello' => 'Hello'
);


And when I try to show the word in the view using function trans it gives me the code from the view, not the word.

{{ trans('greetings.hello') }}


Any ideas?

Answer

You can manage this by creating a middleware group.

//middleware
use Closure, Session;

class ManageLocalization {

protected $languages = ['en','de'];

public function handle($request, Closure $next)
{
    if(!Session::has('userLang'))
    {
        Session::put('userLang', $request->getPreferredLanguage($this->languages));
    }
    app()->setLocale(Session::get('userLang'));

    return $next($request);
}

}

add this to kernel.php

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\ManageLocalization::class
    ],

protected $routeMiddleware = [
    'userLang' => \App\Http\Middleware\ManageLocalization::class
];