阻止访问页面students.index()

时间:2019-07-29 21:09:49

标签: laravel authentication laravel-5

在我的导航栏中,我有2个页面,分别是Student AddStudent Index

enter image description here

当我单击“学生添加”时,我收到一条错误消息Access Denied。 很好,没问题...

enter image description here

现在,我想在页面Students Index上显示偶数并显示项目,我有问题。

我有权访问内容...

enter image description here

在我的控制器学生中,我有这个:

class StudentController extends Controller
{   

    public function __construct()
    {
        $this->middleware(['auth', 'clearance'])
            ->except('index', 'show');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $students = Student::orderby('id', 'desc')->paginate(5);
        return view('students.index', compact('students'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('students.create');
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $this->validate($request, [
            'name'=>'required',
            'firstname' =>'required',
            ]);

        $name = $request['name'];
        $firstname = $request['firstname'];

        $student = Student::create($request->only('name', 'firstname'));

        return redirect()->route('students.index')
            ->with('flash_message', 'Article,
             '. $student->name.' created');
    }

然后,在我的班级 ClearanceMiddleware 中,我有了这个:

public function handle($request, Closure $next) {        
        if (Auth::user()->hasPermissionTo('Administer roles & permissions')) {
            return $next($request);
        }

        if ($request->is('students/create')) {
            if (!Auth::user()->hasPermissionTo('Create Student')) {
                abort('401');
            } else {
                return $next($request);
            }
        }

        if ($request->is('students/index')) {
            if (!Auth::user()->hasPermissionTo('Index Student')) {
                abort('401');
            } else {
                return $next($request);
            }
        }

我看不到错过的步骤。我必须禁止访问。

2 个答案:

答案 0 :(得分:1)

$ this->中间件(['auth','clearance'])             -> except('show');

从except方法中删除索引。因为是这样,所以您无需从中间件检查中使用索引方法。

答案 1 :(得分:1)

2件事:

1)您需要在控制器的构造函数中调整中间件调用。 except()方法意味着中间件不会在这些方法上运行,因此,如果您希望中间件在index方法上运行,则需要将其从except()中删除。

这将在除show()之外的所有路由方法上调用中间件:

$this->middleware(['auth', 'clearance'])
    ->except('show');

2)在中间件内部,您正在使用$request->is()在路径上进行匹配,但是index的网址不是'students / index'。

// The url path for the index route is '/students'
if ($request->is('students')) {
    if (!Auth::user()->hasPermissionTo('Index Student')) {
        abort('401');
    } else {
        return $next($request);
    }
}