英文:
Laravel middleware logout
问题
以下是翻译好的内容:
我想在我的Laravel 9项目中创建一个中间件,如果用户不活跃,他们会自动注销。在我的中间件类中,如下所示。
public function handle(Request $request, Closure $next)
{
if (Auth::user()->is_active != 1) {
return Auth::logout();
}
return $next($request);
}
但是当我尝试时,我收到了以下错误。
我做错了什么吗?
英文:
I want to make a middleware in my Laravel 9 project where if the user is inactive, they automatically get logged out. In my middleware class, like the following.
public function handle(Request $request, Closure $next)
{
if (Auth::user()->is_active != 1) {
return Auth::logout();
}
return $next($request);
}
But when I try it, I get an error like this.
Am I doing something wrong?
答案1
得分: 1
"登出功能不会返回对象,并且您无法从中间件中重定向它。您可以做的是:
public function handle(Request $request, Closure $next)
{
if (Auth::check() && Auth::user()->is_active != 1) {
Auth::logout();
return redirect('/login'); # 添加您的登录路由
}
return $next($request);
}
```"
<details>
<summary>英文:</summary>
**The logout function will not return the object, and you can't redirect it from middleware.**
What you can do is
public function handle(Request $request, Closure $next)
{
if (Auth::check() && Auth::user()->is_active != 1) {
Auth::logout();
return redirect('/login'); # add you login route
}
return $next($request);
}
</details>
# 答案2
**得分**: 0
You're pretty close, just some minor changes are needed.
所以问题在于您的中间件通常会返回 `$next($request);`,否则它将破坏 Laravel 的内部管道 (您可以阅读这篇优秀的博文以了解更多关于中间件和管道的内容 [Understanding Laravel Pipelines](https://jeffochoa.me/understanding-laravel-pipelines))。
但是在您的情况下,返回这个可能不起作用,因为您的 `auth` 中间件必须在此之前已经执行过了。
处理这个问题的最简单方式是注销并中止操作(假设在这种情况下您想要返回一个 401 响应),类似于:
```php
public function handle(Request $request, Closure $next)
{
if (Auth::user()->is_active != 1) {
Auth::logout();
abort(401, 'User is not active');
}
return $next($request);
}
英文:
You're pretty close, just some minor changes are needed.
So the problem is that your middleware would usually return the $next($request);
, otherwise it would break Laravel's internal pipeline (You can read this good blog post to understand more about middleware and pipelines Understanding Laravel Pipelines).
But returning that will probably not work in your case since your auth
middleware must have already been executed before this.
The easiest way to handle this would be to logout and abort (Assuming that returning a 401 response is what you would like in this scenario), something like
public function handle(Request $request, Closure $next)
{
if (Auth::user()->is_active != 1) {
Auth::logout();
abort(401, 'User is not active');
}
return $next($request);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论