我有一个选择菜单,供用户选择3种语言(英语,西班牙语和德语)中的1种。目的是,如果用户选择英语,则网站的所有内容都将变为英语,其他语言也将变为相同。
我有下面的代码,但是没有用。出现missing required parameter for route site.translate
。
LanguageController:
class LanguageController extends Controller
{
public function changeLanguage($language)
{
if(Session::has(locale)){
session()->set('locale', $language);}
else{
session()->set('locale', 'en');
}
return redirect()->back();
}
}
HTML:
<div class="col-6 col-lg-3 pt-4 pb-4">
<div class="footer-list">
<h3>Language</h3>
<form method="get" action="{{route('site.translate')}}">
{{csrf_field()}}
<select name="language" class="form-control font-weight-normal text-gray" id="exampleFormControlSelect1">
<option selected class="selected" value="de">German</option>
<option value="en">English</option>
<option value="de">German</option>
<option value="es">Spanish</option>
</select>
</form>
</div>
</div>
LocaleMiddleware:
<?php
namespace App\Http\Middleware;
use Closure;
class LocaleMiddleware
{
protected $languages = ['en','fr','es', '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);
}
}
路线:
Route::get('lang/{language}', [
'uses' => 'LanguageController@changeLanguage',
'as' =>'site.translate'
]);
答案 0 :(得分:0)
问题是您的路线需要参数。 lang/{language}
在执行表单发布时,您不需要参数。另外,您需要将表单设置为POST
而不是GET
请改做类似的事情。
路线:
Route::post('/lang', [
'uses' => 'LanguageController@changeLanguage',
'as' =>'site.translate'
]);
查看:
<div class="col-6 col-lg-3 pt-4 pb-4">
<div class="footer-list">
<h3>Language</h3>
<form method="post" action="{{route('site.translate')}}">
{{csrf_field()}}
<select name="language" class="form-control font-weight-normal text-gray" id="exampleFormControlSelect1">
<option selected class="selected" value="de">German</option>
<option value="en">English</option>
<option value="de">German</option>
<option value="es">Spanish</option>
</select>
</form>
</div>
</div>
控制器:
class LanguageController extends Controller
{
public function changeLanguage(Request $request)
{
if(Session::has(locale)){
session()->set('locale', $request->language);}
else{
session()->set('locale', 'en');
}
return redirect()->back();
}
}