Laravel - 从中​​间件发送数据到路由

时间:2021-04-06 12:46:44

标签: php laravel middleware

我正在尝试从中间件中的句柄函数发送一些数据:

<?php

namespace App\Http\Middleware;

class LanguageSwitcher
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!Session::has('locale'))
         {
           Session::put('locale',Config::get('app.locale'));
        }
        App::setLocale(session('locale'));
        
        $locale = session('locale'); // => The data I want to send
        
        return $next($request);
    }
}

我的 web.php:

Route::group(['middleware'=>'language'], function () {
    // I want to set the prefix to locale here, but it's undefined
    Route::group(['prefix' => $locale], function () {

    });
});

我尝试使用 Session::get('locale') 获取 web.php 中的 $locale,但我得到 Null。 那么,有没有办法从中间件发送到路由?

3 个答案:

答案 0 :(得分:0)

这篇文章会有所帮助 本文将向您展示如何使用 Auth 处理路由和多语言路由和区域设置中的语言变量。 https://laraveldaily.com/multi-language-routes-and-locales-with-auth/

答案 1 :(得分:0)

我来宾您想使用语言环境来支持多语言。您可以在中间件中设置语言环境并在您的路由中使用语言环境。这是我的示例 https://pastebin.pl/view/c5034cb9

答案 2 :(得分:0)

我不知道,试试这个:

# File: YourApp/routes/web.php

/*
 * Return the locale
 */
function getLocate() {
  if (!Session::has('locale')) {
     Session::put('locale', Config::get('app.locale'));
     return Config::get('app.locale');
  }
  return Session::get('locale');
}


Route::group(['middleware'=>'language'], function () {
    Route::group(['prefix' => getLocate()], function () {

    });
});