如何在Laravel上使用多个中间件组? [英] How to use multiple Middleware groups on Laravel?

查看:1215
本文介绍了如何在Laravel上使用多个中间件组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将路由访问限制为我使用Laravel 5.7编写的网站中的某些类型的用户,现在我正在尝试使用中间件.

I'm trying to restrict the access of routes to only some types of users in my site that I'm writing with Laravel 5.7, right now I'm trying to do it with middlewares.

对于每个用户级别,我都有一个带有以下代码的中间件(类型有所不同):

For each user's level I have a middleware with this code(with a variation on the type):

public function handle($request, Closure $next)
{
    if(Auth::user()->type==3)
        return $next($request);
    else
        return redirect()->route('dashboard');
}

kernel.php 文件中,我将它们编写为:

And in the kernel.php file, I have them written like this:

protected $routeMiddleware = [
    ...
    'teacher' => \App\Http\Middleware\RedirectIfTeacher::class,
    ...
]

在我的应用程序中,每个用户都有一个从1到5的级别,但是每个级别都有单独的视图和一些共享的视图,但是我不能只为一种类型的用户重定向视图,因为我可以当我在与两种以上类型的用户共享的一条或多条路由上使用多个中间件时,就不能使它们正常工作.

In my application each user has a level, which starts from 1 to 5, but each level has individual views and some shared views, but I can't manage to redirect views for more than just one type of user because I can't make them work when I use more than one middlewares on a route (or routes) that are shared with more than two types of users.

当我尝试操作时,它会忽略第二个或多个中间件,并重定向到路由 dashboard ,这是如果用户类型无法输入所需视图时进行重定向的路由.

When I try it justs ignores the second or more middlewares and redirects to the route dashboard which is the route for redirecting if the type of user can't enter the desired view.

现在我已经尝试使用以下代码:

Right now I've tried with this code:

Route::group(['middleware' => ['administrator','teacher','student']], function(){

并使用以下代码:

Route::group(['middleware' => ['administrator' OR 'teacher' OR 'student']], function(){

我也尝试过这种风格:

Route::group(['middleware' => ['administrator|teacher|student']], function(){

没有运气,我在做错什么吗?还是有更好的方法来完成我要达到的目标,请先谢谢!!

Without getting any luck, is there anything what am I doing wrong? or is there a better way to do what I'm trying to achieve, thanks in advance!.

推荐答案

我正在使用下面的代码,它的工作原理是:

I'm using below code and it worked:

Route::group(['middleware' => ['administrator','teacher','student']], function() {});

1在kernel.php文件中,您是否已获得与中间件一起分配的所有键?例如:

1 In the kernel.php file, have you got all of the keys assigned with your middlewares ? For example:

protected $routeMiddleware = [
...
'administrator' => \App\Http\Middleware\RedirectIfAdmin::class,
'teacher' => \App\Http\Middleware\RedirectIfTeacher::class,
'student' => \App\Http\Middleware\RedirectIfStudent::class,
...
]

2尝试在handle()中的if之前检查用户变量.

2 Try to check the user vars before the if in your handle().

dd(Auth::user()->type);

这篇关于如何在Laravel上使用多个中间件组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆