简体   繁体   English

问:如何在 laravel 中的 controller 中制作条件构造函数语句

[英]Q: How to make conditional constructor statement within a controller in laravel

I have a controller which uses two models of authenticatable type of users, if i'm authenticated as an applicant it successfully renders the applicant.index view, and the same thing goes to if I'm authenticated as an Employer.我有一个 controller ,它使用两种可验证类型的用户模型,如果我被验证为申请人,它会成功呈现applicant.index .index 视图,如果我被验证为雇主,也会发生同样的事情。 The issue for me is when I'm not logged in and visits the /app it renders empty page.对我来说,问题是当我没有登录并访问/app时,它会呈现空白页面。

How can protect this route and redirect to for example '/' route.如何保护此路由并重定向到例如'/'路由。

A controller that indexes two models with two different views:一个 controller 索引具有两个不同视图的两个模型:

class ProfilesController extends Controller
{

    public function index()
    {

    if (auth('applicant')->check())
    {
        
        $applicants = Applicant::where('id', '!=', Auth::guard('applicant')->user()->id)->get();
        return view('applicant.index', compact('applicants'));

    } elseif (auth('employer')->check()) {
        
        $employers = Employer::where('id', '!=', Auth::guard('employer')->user()->id)->get();
        return view('employer.index', compact('employers'));

    }
    }
}

using this following route:使用以下路线:

Route::get('/app/', 'Profiles\ApplicantController@index');

I have tried this piece of code but it's not working:我已经尝试过这段代码,但它不起作用:

public function __construct()
    {
        if (auth('applicant')->check())
        {
            $this->middleware('auth:applicant');
        } elseif  (auth('employer')->check()) {
            $this->middleware('auth:employer');
        } else {
           return abort(404);
        }

    }

the else statement takes over even if i'm authenticated and returns 404 .即使我通过了身份验证, else 语句也会接管并返回404

The constructor of the Controller is hit before the Request is passed through the middleware stack (This is how Laravel can actually get the middleware you assign in the constructor for the Controller). Controller 的构造函数在请求通过中间件堆栈之前被命中(这就是 Laravel 实际上可以获取您在构造函数中为控制器分配的中间件的方式)。 This means the session has not started yet so you won't have access to auth or the session at that point.这意味着 session 尚未启动,因此此时您将无法访问 auth 或 session。

The auth middleware itself takes a variable amount of parameters as guards; auth中间件本身采用可变数量的参数作为保护; you can pass it multiple guards for it to check:您可以将多个警卫传递给它以进行检查:

'auth:applicant,employer'

This will spin through all those guards and if one of them returns a User it will set that guard as the default and let the Request pass through.这将遍历所有这些守卫,如果其中一个返回用户,它将将该守卫设置为默认值并让请求通过。 If it spins through the guards and none of them authenticate then the Request is not passed through (auth failed).如果它通过警卫旋转并且它们都没有进行身份验证,则请求不会通过(身份验证失败)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM