TransWikia.com

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

Stack Overflow Asked by seddka on January 5, 2022

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. The issue for me is when I’m not logged in and visits the /app it renders empty page.

How can protect this route and redirect to for example '/' route.

A controller that indexes two models with two different views:

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/', 'ProfilesApplicantController@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.

One Answer

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). This means the session has not started yet so you won't have access to auth or the session at that point.

The auth middleware itself takes a variable amount of parameters as guards; 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).

Answered by lagbox on January 5, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP