問題描述
$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 Pandey、Marcin Nabiałek)