简体   繁体   English

我如何在 Controller 索引 Laravel 7 中检查身份验证

[英]How do i check Authentification in the Controller Index Laravel 7

everyone, I am fairly new to laravel I am currently working on a HR System project and I am creating a Leave managment where the user employee can ask for a leave of sort and the manager and admin can accept or deny it and it was going pretty well until at some point i dont know why but the user can still see what the admin should see he can still enter through the link even when the files are in the admin folder so i tried to do an if with Auth but it wasnt working and its giving me this error大家,我对 laravel 还很陌生好吧,直到某个时候我不知道为什么,但是用户仍然可以看到管理员应该看到的内容,即使文件位于管理员文件夹中,他仍然可以通过链接输入,所以我尝试使用 Auth 进行 if 但它不起作用并且它给了我这个错误

"Trying to get property 'role_id' of non-object" “试图获取非对象的属性 'role_id'”

This is the code im using for the if in the index这是我在索引中用于 if 的代码

LeaveController离开控制器

public function index()
    {
        $leaves = Leave::latest()->get();

       if(Auth::user()->role_id == 1){
        return view('/home');
       }
       elseif(Auth::user()->role_id == 2){
        return view('admin/leave/index', compact('leaves'));
       }
       else{
           return view('admin/leave/index', compact('leaves'));
       }
        
    }

Employee has a role based id 1 and Manager has role id of 2 but the super admin doesnt have it he just exists like a default admin with all permissions thats why i just left it at else员工的角色 ID 为 1,经理的角色 ID 为 2,但超级管理员没有它,他只是像默认管理员一样存在,拥有所有权限,这就是为什么我把它留在 else

If you have check if someone is an admin to continue the page you can make a middleware.如果您检查某人是否是管理员以继续该页面,您可以制作一个中间件。

php artisan make:middleware CheckAdmin

Route::get('admin/profile', function () {
    //
})->middleware('Admin');

and on the web.php file attach the middleware to the route.并在 web.php 文件上将中间件附加到路由。

Check the laravel docs for detailed information https://laravel.com/docs/7.x/middleware查看 laravel 文档以获取详细信息https://laravel.com/docs/7.x/middleware

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM