Laravel: 使用isAdmin列检查用户是否是管理员?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Laravel: 使用isAdmin列检查用户是否是管理员?相关的知识,希望对你有一定的参考价值。

我对laravel是个新手, 我一直在阅读文档和教程. 我打算做一个有2个角色的应用程序, 即管理员和用户. 我修改了我的User模型,使 "isAdmin "列具有布尔值,因为我只需要两个角色。我如何在auth期间对这个属性进行检查?谢谢你。

答案

回答你的问题,首先,要使用auth中间件来保护任何路由,确保用户在访问路由之前已经通过认证(登录),你只需要添加auth中间件,例如

web.php

<?php
Route::middleware('auth')->group(function(){
//All Routes which needs user to be logged in
});

or 

//Individiual Route Middleware
Route::get('/path/to', 'controller@instance')->middleware('auth');

至于检查用户角色,你基本上可以通过以下步骤创建一个中间件来实现。

  1. 运行你的php artisan make:middleware IsAdminMiddleware。
  2. 打开你的IsAdminMiddleware并在句柄函数中添加这段代码。

    public function handle($request, Closure $next) { if(!Auth::check()){ return redirect()->route('login'); }。

            if(Auth::user()->isAdmin == true){
                return $next($request);
            }
    
            return redirect()->back()->with('unauthorised', 'You are 
              unauthorised to access this page');
        }
    

以上是关于Laravel: 使用isAdmin列检查用户是否是管理员?的主要内容,如果未能解决你的问题,请参考以下文章