user1604220
user1604220

Reputation: 161

Laravel 5 - creating a middleware that works for two controllers

I am creating a vote site, where at first the user has to enter his username. That page introduces him to the website. After he enters his username and submits it, I set up a new session under his username he entered and then I redirect him to the actual voting page.

Okay, so now I need to redirect the user to the vote page if he tries to access the introduction page (where he enters his username) only if the session still exists with his username, if not, keep him there.

So what I did is created a simple UsernameMiddleware:

public function handle($request, Closure $next)
{
    if (Session::get('username') != null) {
        return redirect()->route('vote');
    }
    return $next($request);
}

And in the LoginController I set the middleware:

    $this->middleware('user');

But now, I have the VoteController which should do the opposite of what the UserMiddleware does for LoginController, this time it should check if the session doesn't exist, if true, redirect to the login introduction page (where he enters his username and such).

I could create another middleware for that, but I think that this is bad practice to do and it should use one middleware for that. I think the middleware should receive some kind of a service or a domain injected and then it should check what controller we use currently etc and then base our checks on that, but I am not sure.

What is the best practice to handle things like that?

Thank you a lot!

Upvotes: 0

Views: 78

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152870

Two middlewares is actually not bad practice at all. The framework even has it out of the box!

There's auth (Authenticate) and guest (RedirectIfAuthenticated) which basically do exactly what you describe (except that it uses the "real" built in login system).

So don't worry about creating a second middleware. Middleware should be pretty thin in code anyways so you don't create much (if at all) duplicate code here.

Upvotes: 1

Related Questions