我试图用两种语言动态显示文本 - 英语或德语。但是我没有完成任务,因为没有任何反应。
我做了以下事情:
中间件:
public function handle($request, Closure $next) {
if (!\Session::has('locale')) {
\Session::put('locale', \Config::get('app.locale'));
}
app()->setLocale(\Session::get('locale'));
return $next($request);
}
}
控制器:
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Session;
use App;
use Illuminate\Http\Request;
class LanguageController extends Controller {
protected $langs = ['en', 'de'];
public function changeLanguage($lang) {
if (in_array($lang, $this->langs)) {
App::setLocale($lang);
Session::put('locale', $lang);
}
return redirect()->back();
}
}
内核:
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
\App\Http\Middleware\TrustProxies::class,
\App\Http\Middleware\LanguageMiddleware::class,
];
查看:
<div class="dropdown">
<button class="dropbtn">{{trans('translations.lang')}}</button>
<div class="dropdown-content">
@if(Session::get('locale')=='en')
<a href="lang/de">Deutsch</a>
@else
<a href="lang/en">English</a>
@endif
</div>
</div>
路线:
Route::get('lang/{id}', 'LanguageController@changeLanguage');
使用Laravel 5.4
提前致谢:)
答案 0 :(得分:0)
你可以像这样定义和中间件:
namespace App\Http\Middleware;
use Closure;
/**
* Class LocaleMiddleware.
*/
class LocaleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
*/
protected $languages = ['en','de'];
public function handle($request, Closure $next)
{
if(!session()->has('locale'))
{
session()->put('locale', $request->getPreferredLanguage($this->languages));
}
app()->setLocale(session('locale'));
return $next($request);
}
}
控制器上的创建更改方法
public function changeLanguage($languague)
{
if(Session::has(locale)){
session()->set('locale', $language);}
else{
session()->set('locale', 'en');
}
return redirect()->back();
}
路线看起来像
Route::get('lang/{languague}', 'LanguageController@changeLanguage');
答案 1 :(得分:-1)
在你的路线命令中发送$ id,但在你的控制器功能中输入$ lang而不是$ id。这个错误就可以了。
你必须拥有这个
public function changeLanguage($id) {