I'm using laravel 5.1, I'm trying to update locale in app file like this: In Locale Middleware file:
...
public function handle($request, Closure $next)
{
if(Session::has('locale'))
{
$lang = Session::get('locale');
App::setLocale($lang);
}
return $next($request);
}
Any idea about this??
Oooof finally after two hours ><'.: It's the line place of locale class in middleware -.-' !!! I set it in last line like this :
...
...
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\Locale::class,
];
and All is fine and working: thanks for you all :))))
The only solution which I found was set locale in constructor method of middle ware, like this:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
class Localization
{
protected $app;
public function __construct(Application $app, Request $request)
{
if($locale = $request->header('Content-Language')){
if(in_array($locale, ['en', 'fa'])){
$app->setLocale($locale);
}
}
}
/**
* Handle an incoming request.
*
* @param Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request);
}
}
With ♥♥♥ and over 2 hours trying!
Thanks,
:) I had the same problem and the solution was put the middleware in the file App\Http\Kernel.php in the section of protected $middleware = []
\App\Http\Middleware\VerifyCsrfToken::class,
\App\Http\Middleware\myNewMiddleware::class,
];
I have solved my issue as follow:
1 Step. Created a middleware . php artisan make:middleware SetLocale
2 Step. Updated the middleware file. File: app/Http/Middleware/SetLocale.php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
class SetLocale
{
private $locales = ['ar', 'en'];
// ...
public function handle($request, Closure $next, $locale)
{
if (array_search($locale, $this->locales) === false) {
return redirect('/');
}
App::setLocale($locale);
return $next($request);
}
}
3 Step. Appended my new middleware to app/Http/Kernel.php
$routeMiddleware
array.
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
// ...
protected $routeMiddleware = [
// ...
'locale' => \App\Http\Middleware\SetLocale::class,
];
}
4 Step. I have used my the middleware in my routes/web.php
file.
Route::group(['prefix' => 'ar', 'namespace' => 'Arabic', 'middleware' => 'locale:ar'], function() {
Route::get('/', 'PashtoHomeController@index')->name('arHome');
// ...
});
Route::group(['prefix' => 'en', 'namespace' => 'English', 'middleware' => 'locale:en'], function() {
Route::get('/', 'PashtoHomeController@index')->name('enHome');
// ...
});
Route::get('/', function() {
return redirect()->route('arHome');
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.