Laravel 10 Auth::user() – 尝试在空值上读取属性

huangapple go评论51阅读模式
英文:

Laravel 10 Auth::user() - Attempt to read property on null

问题

以下是您要翻译的内容:

All I am trying to do is make a middleware where only user with role_id = 1 can access the dashboard.

Now keep in mind I didn't use laravel/breeze, instead I used laravel/ui auth.

Here is my checkRole middleware:

public function handle(Request $request, Closure $next): Response
{
    if (Auth::user()->role_id != 1)
    {
        return redirect()->route("welcomepage");
    } 

    return $next($request);
}

Here is the middleware in web.php:

Route::middleware(["checkRole"])->group(function() {
    Auth::routes(["register" => false, "reset" => false]);
    // I use these parameters because I don't want these routes
});

I have used the same middleware before with laravel/breeze and had no problem but now with laravel/ui auth I get this error.

英文:

All i am trying to do is make a middleware where only user with role_id = 1 can access the dashboard.

Now keep in mind i didn't use laravel/breeze, instead i used laravel/ui auth

Here is my checkRole middleware:

public function handle(Request $request, Closure $next): Response
{
    if(Auth::user()->role_id != 1)
    {
        return redirect()->route("welcomepage");
    } 

    return $next($request);

}

Here is the middleware in web.php :

Route::middleware(["checkRole"])->group(function() {
    Auth::routes(["register" => false, "reset" => false]);
    //I use these parameters because i don't want these routes
});

I have used the same middleware before with laravel/breeze and had no problem but now with laravel/ui auth i get this error.

答案1

得分: 0

以下是翻译好的部分:

在我输入问题的时候,我随机想到了解决方法。laravel/ui authHomeController.php 中的构造方法中列出了中间件。

现在的代码如下:

public function __construct()
{
    $this->middleware('auth');
    $this->middleware('checkRole'); // 刚刚添加的
}

而在 web.php 中,我只移除了中间件,现在如下:

Auth::routes(["register" => false, "reset" => false]);

middleware 方法保持不变。

英文:

While i was typing the question i randomly came with the solution. laravel/ui auth in the HomeController.php in the constructor method are the middlewares listed

This is how it looks now:

public function __construct()
{
    $this->middleware('auth');
    $this->middleware('checkRole'); //just added it
}

And in web.php i just removed the middleware and have only:

Auth::routes(["register" => false, "reset" => false]);

The middleware method stays the same.

答案2

得分: 0

添加中间件验证用户是否为访客。

英文:

Add to middleware validation if user is guest

huangapple
  • 本文由 发表于 2023年2月24日 05:38:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550579.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定