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


問題描述

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

我正在創建一個中間件,它將處理授權說檢查角色然後授權。但是當我在做 $role = $request‑>user()‑>role;

它給了我錯誤 嘗試獲取非屬性對象。我在這裡做錯了什麼。

這是我的中間件類的摘錄

RoleMiddleware

namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use App\Http\Requests;

class RoleMiddleware
{
    public function handle($request, $next) {
    $role = $request‑>user()‑>role;

另外我想知道區別並想知道哪個最好,我應該授權使用中間件、Policy 還是門面?

感謝您的幫助,

謝謝,Sambhav


參考解法

方法 1:

There is no "best" way method to authorize users. You can use Middleware, Policies or Gate or mix them together.

In your case the problem is:

$role = $request‑>user()‑>role;

because user is not always logged in.

So you should change it like so:

$role = $request‑>user() ? $request‑>user()‑>role: 'guest';

to set guest role for not logged user and to get rid of error.

(by Kumar Sambhav PandeyMarcin Nabiałek)

參考文件

  1. $request‑>user()‑>role errror ‑ trying to get property of non‑object (CC BY‑SA 2.5/3.0/4.0)

#laravel-middleware #laravel-5 #laravel-5.2 #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)







留言討論