在 laravel 5.1 中檢查管理員角色 (Checking admin roles in laravel 5.1)


問題描述

在 laravel 5.1 中檢查管理員角色 (Checking admin roles in laravel 5.1)

我正在使用 Laravel 框架做我的項目。一切似乎都很完美。但是,在我的登錄部分,我想做一些事情,比如當用戶登錄系統時,它會檢查“is_admin”列。如果“is_admin”列等於 1,它將直接進入管理頁面。我一直在互聯網上尋找,但我找不到這個問題的答案。我也確實使用了中間件,但它沒有用。我不知道為什麼。有人可以幫我解決這個問題。謝謝


參考解法

方法 1:

Laravel 5.1 allows authorization, you can add something like this in your AuthServiceProvider

public function boot(GateContract $gate){
    $gate‑>define('admin', function($user){
        return $user‑>is_admin;
    });
}

Then use the Gate facade in your controllers like

$user=Auth::user();
if(Gate::allows('admin', $user)){
    //user is admin
}

Take a look at this part of Laravel's documentation http://laravel.com/docs/5.1/authorization

方法 2:

You can write this in your AuthController.php

if(Auth::user()‑>is_admin == 1){
    protected $redirectTo = 'admin';
}else{
    protected $redirectTo = 'member';
}

The avobe code is only for redirection. You can use middleware to protect admin panel from member.

(by Huy LeSaadsmartrahat)

參考文件

  1. Checking admin roles in laravel 5.1 (CC BY‑SA 2.5/3.0/4.0)

#laravel-middleware #Laravel #PHP






相關問題

使用中間件進行表操作 laravel 5.1 (Using middleware for table manipulation laravel 5.1)

Laravel 中間件“僅”為每條路線觸發 (Laravel middlware 'only' fires for every route)

在 laravel 5.1 中檢查管理員角色 (Checking admin roles in laravel 5.1)

在laravel 5中使用中間件重定向循環 (redirect loop with middleware in laravel 5)

Laravel - 中間件後清空 $request (Laravel - Empty $request after middleware)

$request->user()->role 錯誤 - 試圖獲取非對象的屬性 ($request->user()->role errror - trying to get property of non-object)

檢測到 Laravel 中間件但未執行 (Laravel middleware detected but not executed)

將 Auth 中間件應用於所有 Laravel 路由 (Apply Auth Middleware to All Laravel Routes)

路由組內的功能 [laravel-passport] (Function inside route group [laravel-passport])

當我嘗試訪問主頁時,Laravel 不會重定向到登錄頁面 (Laravel does not redirect to login page when I try to access to home page)

控制器沒有來自中間件的更改請求 (Controller doesnt have the alter request from the middleware)

訂閱者中間件路由允許公眾查看所有受限頁面 (Subscriber middleware route allowing public to view all restricted pages)







留言討論