我在提交表单时在网址中获取正确的语言参数时遇到问题。
我的应用程序有两种可能的语言参数:de
和en
。
我用这个函数创建了一个名为setLocale.php的中间件:
public function handle($request, Closure $next)
{
$locale = $request->segment(1);
app()->setLocale($locale);
return $next($request);
}
这是web.php中的路由:
Route::post('/{locale?}/ticket', 'TicketController@store')->name('validation');
这是表单操作:
<form method="post" action="{{ route('validation') }}">
当我想提交表格并验证输入时,您应该到达我在上面显示的路线。
但网址只会是:/ticket
而不是en/ticket
或de/ticket
。
顺便说一句,你通过链接到达表单站点,所以语言参数是静态的,如下所示:
Route::get('/en/index/{param1?}/{param2?}', 'TicketController@index')->name('index');
Route::get('/de/index/{param1?}/{param2?}', 'TicketController@index')->name('index');
handle
中间件中的setLocale.php
函数不应该为我提供语言参数吗?
如果是,我怎样才能将其传递到下一页(通过表单操作)?编辑
当我像这样编辑表单操作时它工作正常:
<form method="post" action="{{ route('validation', app()->getLocale()) }}">
这会是一个很好的解决方案吗?
据我所知,你的问题是如果没有明确地将一个{locale}
函数传递给route()
函数,那么route binding参数没有值。您可以使用Route::bind('locale', function ($value) {
if (!$value) {
$value = app()->getLocale();
}
return $value;
});
(请参阅“自定义分辨率逻辑”)以确保它始终具有值,并回退到当前区域设置:
locale
这指示Laravel在看到名为locale
的路由参数并使用其返回值时调用此函数。如果参数没有值,则返回当前的语言环境。
但请注意,这会影响名为locale
的所有网址参数。如果您有任何允许qazxswpoi参数为空的路由,则必须在其中一个路由中重命名。