代码之家  ›  专栏  ›  技术社区  ›  Js Lim

Laravel:中间件是否可以接受路由输入?

  •  1
  • Js Lim  · 技术社区  · 6 年前

    我想达到的目标是,我在一些国家有听众。我在不同的国家也有编辑。

    例如,美国的编辑器只能在 US ,中的编辑器 Hong Kong 不允许查看我们的帖子。

    Route::get('{country}/posts', [
        'uses' => 'CountryController@posts',
        'middleware' => ['permission:view posts,{country}'], <------- SEE HERE
    ]);
    

    有可能做到这一点吗?

    P/S:我正在使用 Spatie laravel-permission

    2 回复  |  直到 6 年前
        1
  •  0
  •   floflock    6 年前

    这是不可能的,但我在中间件中使用这几行代码:

    $country = $request->route('country'); // gets 'us' or 'hk'
    

    这种方法 Request 返回管段。

        2
  •  1
  •   IlGala    6 年前

    更容易创建另一个中间件,如下所示:

    namespace App\Http\Middleware;
    
    use Closure;
    
    class CountryCheck
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            // The method `getEnabledCountries` returns an array 
            // with the countries enabled for the user
            if(in_array($request->route('country'), Auth::user()->getEnabledCountries())) {
               return $next($request);
            }
    
            // abort or return what you prefer
    
        }
    }
    

    不管怎样。。。这个 country

    在我看来,最好创建一条 Route::get('posts') 在控制器内加载与用户国家相关的帖子。。。类似于:

    Post::where('locale', '=', Auth::user()->locale())->get()

    Post::whereLocale(Auth::user()->locale())->get()