是否可以覆盖back()函数中的参数

时间:2019-09-28 08:38:01

标签: php laravel routes localization

我这里有一个简单的问题。

这是我的代码

  1. 路线
Route::post('change-language', 'LanguageController@changeLanguage')->name('changeLanguage')->middleware('localization');
  1. 本地化中间件
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);
        }
    }
  1. changeLanguage函数
public function changeLanguage(Request $req)
    {
        return redirect()->back();
    }

正如您在本地化中间件中所看到的,我根据路由URL更改了语言。当我更改changeLocalization之类的收益return redirect($req->lang)时,它就像是一种魅力。但我想重定向回到以前的路线。是否可以在back()函数中添加或覆盖路由参数?

1 个答案:

答案 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'],

测试

  • 转到domain.tld / about 页面是英文
  • 将URL更改为domain.tld / lang / fr 您被重定向回/ about,并且页面为法语

希望这会有所帮助