我试图创建一个表单,并取消Ajax。是的,当我var_dump它并退出时,表单至少会将参数发送到控制器以查看它是否获得了新值,是的,它确实获得了新值,但你猜怎么着?问题是:
即使从控制器接收到的Input::get('locale')是我从表单发送的,下面的代码也不能改变会话。
控制器:
public function languagechooser()
{
$session = Input::get('language');
var_dump($session);exit;
Session::set('locale',$session);
returnRedirect::back();
}
改变会话的唯一方法是硬编码它,像这样(注意'en':
public function languagechooser()
{
$session = Input::get('language');
var_dump($session);exit;
Session::set('en');
returnRedirect::back();
}
但我不明白为什么。一旦它从变量接收到它,它应该留在那里,但看起来它没有。它到底是一个变量吗?但在youtube上phpacademy做同样的事情(只是使用Laravel 4),而我使用5
和Form,只是一个Form
<form action="{!!URL::route('languagechooser')!!}" method ="post">
<select class="form-control" name="language">
<option value="fr">fr</option>
<option value=en">en</option>
<option value="es">es</option>
<option value="ru">ru</option>
<option value="it">it</option>
<option value="de">de</option>
</select>
<button class="btn btn-primary pull-right" type="submit">Search</button>
{!!Form::token()!!}
</form>
routes.php
Route::get('/', 'WelcomeController@index');
Route::post('languagechooser', [
'as' => 'languagechooser',
'uses' => 'WelcomeController@changeLanguage'
]);
view - welcome.blade.php
<!-- I think this bit should help you out! -->
<p>
@if( Session::has('locale') )
Locale: {{ Session::get('locale') }} <br>
Message: {{ Lang::get('test.message') }}
@else
no session locale set
@endif
</p>
<form action="{!! route('languagechooser') !!}" method = "post">
<select class="form-control" name="language">
<option value="en">en</option>
<option value="es">es</option>
</select>
<button class="btn btn-primary pull-right" type="submit">Search</button>
{!!Form::token()!!}
</form>
Controller - WelcomeController.php
public function changeLanguage()
{
$lang = Input::get('language');
Session::put('locale', $lang);
return Redirect::back();
}
创建中间件:php artisan make:middleware Locale
<?php namespace AppHttpMiddleware;
use Closure;
use Session;
use App;
use Config;
class Locale {
/**
* Handle an incoming request.
*
* @param IlluminateHttpRequest $request
* @param Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$language = Session::get('locale', Config::get('app.locale'));
App::setLocale($language);
return $next($request);
}
}
在HttpKernel.php
文件中添加了这个:'AppHttpMiddlewareLocale'
到$middleware
数组,所以它在每次请求时都被加载。
protected $middleware = [
'IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode',
'IlluminateCookieMiddlewareEncryptCookies',
'IlluminateCookieMiddlewareAddQueuedCookiesToResponse',
'IlluminateSessionMiddlewareStartSession',
'IlluminateViewMiddlewareShareErrorsFromSession',
'AppHttpMiddlewareVerifyCsrfToken',
'AppHttpMiddlewareLocale',
];
资源/lang/en/test.php
return [
'message' => 'hello'
];
资源/lang/es/test.ph"
return [
'message' => 'hola'
];
链接来源:https://laracasts.com/discuss/channels/general-discussion/where-to-setlocale-in-laravel-5-on-multilingual-multidomain-app