douzhenchun6782 2017-12-01 21:03
浏览 158
已采纳

具有OR条件的路径中的Laravel多个中间件

I wonder if I can do this in Laravel Route. Let's say I have Admin, Premium and User (which can be login too by using Auth) Middleware. Also, I have controller with methods like this: index, create, edit, delete and I want Admin to be able do all those things, but Premium can only be able to access index method, and User can't access anything in this controller (he can access another controller). I know I can use except or only middleware method like this:

    public function __construct()
    {
    $this->middleware('premium')->only('index');
    $this->middleware('admin'); 
    // or maybe $this->middleware('admin')->except('index');
    }

but when I try to put these two middlewares in __construct method they will start to conflict each other, it makes sense because index method can be access by Premium Member but then can't be access by the Admin itself. Btw my middleware is simply checking:

    if (Auth::check()) {
        if (Auth::user()->role == 'Admin') {
            return $next($request);
        }
     }
    return redirect('/home');

So, back to my question, can I have OR Middleware so I can avoid conflict from multiple middleware (which is must be AND condition when they written at the same controller constructor)?

Thanks a lot.

  • 写回答

2条回答 默认 最新

  • duannaiying9662 2017-12-01 21:52
    关注

    If you change up the way your logic is thinking a little bit, the answer becomes pretty easy. You can create new middleware that checks if it can access the specific method.

    So create the following middleware 'CanAccessIndex':

    if (Auth::check()) {
        if (Auth::user()->role == 'Admin' || Auth::user()->role == 'Premium') {
            return $next($request);
        }
     }
    return redirect('/home');
    

    Then, you can put that middleware on the index function (instead of the premium middleware) and put your admin middleware on everything EXCEPT index. Like so:

    public function __construct()
    {
        $this->middleware('canAccessIndex')->only('index');
        $this->middleware('admin')->except('index');
    }
    

    That's one way to do it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起