我这里有一个简单的问题。
这是我的代码
Route::post('change-language', 'LanguageController@changeLanguage')->name('changeLanguage')->middleware('localization');
public function handle($request, Closure $next)
{
if (session()->has('locale') && \App\Language::get('lang')->pluck('lang')->contains(Route::getFacadeRoot()->current()->parameter('locale'))) {
$lang = Route::getFacadeRoot()->current()->parameter('locale');
App::setLocale($lang);
session()->put('locale', $lang);
return $next($request);
}elseif(session()->has('locale') && !\App\Language::get('lang')->pluck('lang')->contains(Route::getFacadeRoot()->current()->parameter('locale'))){
$lang = 'id';
App::setLocale($lang);
session()->put('locale', $lang);
return $next($request);
}
}
public function changeLanguage(Request $req)
{
return redirect()->back();
}
正如您在本地化中间件中所看到的,我根据路由URL更改了语言。当我更改changeLocalization
之类的收益return redirect($req->lang)
时,它就像是一种魅力。但我想重定向回到以前的路线。是否可以在back()函数中添加或覆盖路由参数?
答案 0 :(得分:0)
changeLanguage
函数应负责实际更改语言,而不仅仅是重定向
这是我如何做的一个例子
routes/web.php
Route::get('lang/{locale}', 'LocaleController@update')
->name('locale')
->where('locale', '(en|fr|ar)');
// Further filter in route regex (accepts only English, French and Arabic)
LocaleController.php
<?php
namespace Caddy\Http\Controllers;
class LocaleController extends Controller
{
public function update($locale)
{
// Check if the $locale passed is in the array config/app.php => locales
if (in_array($locale, config('app.locales'))) {
// Put the $locale in session with the same name as key
session(['locale' => $locale]);
}
// redirect back
return back();
}
}
Locale.php
中间件
<?php
namespace Caddy\Http\Middleware;
use Closure;
class Locale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$session_locale = session('locale');
if (in_array($session_locale, config('app.locales'))) {
// Keep the locale if already in session
$locale = $session_locale;
} else {
// Fallback to English if not defined
$locale = config('app.locale');
}
app()->setLocale($locale);
return $next($request);
}
}
全局应用中间件
Http\Kernel.php
protected $middlewareGroups = [
'web' => [
\Caddy\Http\Middleware\Locale::class,
],
这是我的config/app.php
'locale' => 'en',
'locales' => ['en', 'fr', 'ar'],
希望这会有所帮助