英文:
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 auth
在 HomeController.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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论