dongtangu8615 2014-12-16 00:20
浏览 505
已采纳

Laravel的自定义过滤器

I have an application with many user roles. Like Admin, Manager etc.

There are some instances where both Manager and Admin has the same permission to see/edit a page. In the route.php I created a filter group for Admin access only.

//filter.php
    Route::filter('admin', function()
    {
        if (Auth::guest() or ! Auth::user()->isAdmin()) {
            return 'Not Authorized';
        }
    });


//route.php
  Route::group(['before' => 'admin'], function(){
    //Some routes.....
  });

Now, I want to check if the user is allowed to view that page by checking the userId and the courseId. How can I get these values in the filter.php?

I have a function which checks if the user is authorized for that page. But it requires two variables to be passed (Atleast one variable, the courseId)

public static function isAllowed($userId, $courseId){
//Some conditions. 
}

How can I do this?

  • 写回答

1条回答 默认 最新

  • douxian1892 2014-12-16 00:38
    关注

    It's quite easy actually. In filter.php you simply need to add your filter function and then use it on the routes.php

    To Decalre a filter for Route::get('my/url/{variable1}/{variable2}):

    Route::filter('myAweSomeFilter', function($route)
    {
        $variable1 = $route->getParameter('variable1');
        if (thisAndThat)
        {
            doStuff;
        }
    });
    

    now, If you want to call a model function, you can do that inside this function.

    Therefore, if you have a model named AuthModel, and a static function named coursePermissionCheck, simply call it as AuthModel::coursePermisssionCheck() and so on. You also write a whole new function inside of the filter function and use it. It's just another function that tells the RouteController what to do if a certain condition is not met.

    How to use this filter: 'before' => 'admin|youFilter'

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我这模型写的不对吗?为什么lingo解出来的下面影子价格这一溜少一个变量
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波