A
A
Alexander Kovalchuk2015-11-17 14:08:19
Laravel
Alexander Kovalchuk, 2015-11-17 14:08:19

How to change language in laravel?

I have a dropdown menu on my site with language selection

<ul>
     <li><a href="/language/en">English</a></li>
     <li><a href="/language/ru">Русский</a></li>
</ul>

Routes redirects to the controller in which the language change is implemented like this:
public function language( $lang ){
  App::setLocale( $lang );
  return redirback();
  }

And the language does not change, what's the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fet, 2015-11-17
@mamut

I didn't like the standard Laravel way.
It is necessary to write a filter, a function, a route, a menu.
Decided to use Laravel Localization
Everything is described in detail, all functions are written. Just paste.
But if you're interested, here's how it worked with standard tools:
Middleware:

public function handle($request, Closure $next)
    {
        $language = Request::cookie('lang', Config::get('app.locale'));

        App::setLocale($language);

        return $next($request);
    }

route:
Route::group([ 'middleware' => ['maintenance_mode', 'locale']], function()
{
    //Change language
    Route::get('set_lang/{id}', ['as' => 'set_lang', 'uses' => '[email protected]_lang']);
}

controller:
public function set_lang($id){
        $response = new \Illuminate\Http\Response('Set Lang');
        return $response->withCookie(cookie()->forever('lang', $id));
    }

The switching menu itself in View:
<li class="dropdown">
                    <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                        {{ trans('main.'.config('app.locales')[Config::get('app.locale')]) }} <i class="fa fa-caret-down"></i>
                    </a>
                    <ul class="dropdown-menu dropdown-langs">
                        @foreach(config('app.locales') as $k=>$val)
                            @if(config('app.locale') != $k)
                                <li><a href="{{ route('set_lang', ['id' = $k]) }}"> {{ trans('main.'.$val) }}</a></li>
                            @endif
                        @endforeach
                    </ul>
                    <!-- /.dropdown-user -->
                </li>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question