Laravel 改进检查用户状态的代码

Laravel improve Code for checking Userstatus

在我的应用程序中,我可以将用户标记为已阻止。在一个被阻止的标记之后,他什么也做不了。

我的解决方案是检查每个构造控制器的状态,如果经过身份验证的用户被标记为已阻止,他将重定向到视图。

但我的解决方案不是很好,因为我有重复的代码,我必须检查实际路线。

这是我的代码:

 public function __construct()
{
    $this->middleware('auth');

    $this->middleware(function ($request, $next)
    {
        $this->user= Auth::user();
        if(strcmp(Route::currentRouteName(),  'user.password.show') != 0)
        {
            if(strcmp(Route::currentRouteName(),  'user.password.set') != 0)
            {

                if(strcmp(Route::currentRouteName(),  'user.blocked.show') != 0)
                {
                    if($this->user->status == Userstatus::where('type', 'passwordSetFalse')->first()->id)
                    {
                        Session::flash('error', 'Bitte setzen Sie ihr Passwort!');
                        return Redirect::route('user.password.show');
                    }
                    else
                    {
                        return $next($request);
                    }
                }else
                {
                    return $next($request);
                }
            }
            else
            {
                return $next($request);
            }
        }
        else
        {
            return $next($request);
        }
    });
}

我搜索了一个解决方案,我把代码放了一次,我可以将它用于我的所有控制器,但我不知道代码可以写在哪里。

非常感谢您的帮助

看看LaravelMiddlewares。定义一个在将请求传递给控制器​​之前检查用户状态的中间件,而不是在 app/Http/Kernel.php.

中注册您的中间件
<?php

namespace App\Http\Middlewares;

class UserBlockedMiddleware
{

    public function handle($request, $next)
    {
         $user = \Auth::user();
         if($user->status == 'blocked') abort(403);

         return $next($request);

    }

}

要了解有关如何注册全局中间件的更多信息,请查看 Laravel 文档中的 section

您需要阅读有关 Protecting Routes

您可以将 auth 中间件附加到您要保护的路由,或者直接在控制器的 __construct

Laravel ships with an auth middleware, which is defined at Illuminate\Auth\Middleware\Authenticate

如果您想要 own Auth middleware 您可以输入以下内容

php artisan make:middleware MyOwnAuth


你也可以这样减少代码

public function __construct()
{
    $this->middleware('auth');

    $this->middleware(function ($request, $next) {
        $this->user = Auth::user();
        if (
            strcmp(Route::currentRouteName(), 'user.password.show') != 0
            && strcmp(Route::currentRouteName(), 'user.password.set') != 0
            && strcmp(Route::currentRouteName(), 'user.blocked.show') != 0
            && $this->user->status == Userstatus::where('type', 'passwordSetFalse')->first()->id
        ) {
            Session::flash('error', 'Bitte setzen Sie ihr Passwort!');
            return Redirect::route('user.password.show');
        };
        return $next($request);
    });
};