juanmiguel431
juanmiguel431

Reputation: 109

How can I change the language of errors in laravel 5.1 dynamically

I have been using the helper

app()->setLocale(session('lang'));

However, I can get to change the languages of views but the languages of errors still continues reading of

\config\app.php locale => ‘es’

That means that always show the same language.

How can i change it also dynamically?

enter image description here

The problems is that the partial view that prints the errors always print in the same language.

Here is the code that i have.

\resources\views\layout.blade.php

@lang('messages.project')
<ul class="nav navbar-nav navbar-right">
  <li><a href="{{ url('lang', ['en']) }}">En</a></li>
  <li><a href="{{ url('lang', ['es']) }}">Es</a></li>
</ul>

\app\Http\routes.php

Route::get('lang/{lang}', 'NotesController@changeLang')->where([ 'lang' => 'en|es']); 

Route::group(['middleware' => ['web']], function () { 
Route::get('notes', 'NotesController@index'); 
Route::get('notes/create', 'NotesController@create'); 
});

\app\Http\Controllers\NotesController.php

public function changeLang($lang)
{
   session(['lang' => $lang]);
   return Redirect::back();
}

\app\Http\Middleware\LangMiddleware.php

public function handle($request, Closure $next)
{
   if (!empty(session('lang'))) {
     app()->setLocale(session('lang'));
   }
   return $next($request);
}

\resources\views\partials\errors.blade.php

<ul>
   @foreach($errors->all() as $error)
      <li>{{ $error }}</li>
   @endforeach
</ul>

Upvotes: 0

Views: 1742

Answers (1)

juanmiguel431
juanmiguel431

Reputation: 109

The solution was put the middleware in the file App\Http\Kernel.php in the section of protected $middleware = [] because i just only put in the section "protected $routeMiddleware"

\App\Http\Middleware\VerifyCsrfToken::class,
    \App\Http\Middleware\myNewMiddleware::class,        
];

Upvotes: 0

Related Questions