Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

BSP's avatar
Level 1

Auth Middleware - custom redirect on some routes.

I have a website that has a public section and an loggedin (dashboard) section.

Eg:

The site is about events created by groups of people, so an event found at the following url: http://site.com/dashboard/group/xxxx/event/yyyy is also available publicly at: http://site.com/event/yyyy

When somebody who is logged in tries to access the public page, we automatically redirect them to the logged in page from the controller. Simple.

The opposite is a bit tricky: When somebody who is not logged in tries to access the logged in event url, they are redirected to the login page by default. This is particularly painful when people try to share the logged in event on facebook by copying the link, and facebook obviously shares the login page :)

The logged in routes are protected by the auth middleware:

Route::resource('dashboard/group/{group}/event', 'Account\EventController')->middleware('auth');

What I want is for the user to be redirected to the public version of the event when they try to reach the "show" method in the controller.

I'm wondering if there's a way to handle exceptions with the auth middleware. I did do a ton of research but was unable to find anything helpful.

0 likes
2 replies
jcmargentina's avatar
Level 8

Ok @BSP , I will help you.

First ,... dont declare the middleware in the routes.php file, declare it IN THE CONTROLLER like this.

class MyController extends Controller
{

    public function __construct() {
        $this->middleware('auth')->except(['show']);
    }
}

then in the controller edit you show() function,like this (attention to the pseudo-code)

    public function show(variable1, variable2, variableN) {

        if ( auth()->check() ) {
                //if the user is logged in ... redirect to some page
            return redirect('/some/url/here');
        } else {
            //if the user is NOT logged in ... redirect to some other page
                return redirect('/other/url/here');
        }
    }

ideally you will treat your own argument variables in the show function n order to properly translate urls, so ... do your coding.

well ... I hope this helps you, please mark the asnwer as correct if is what you needed.

Regards.

BSP's avatar
Level 1

Thank you, jcmargentina, this works well. I didn't know about the 'except' parameter. Pretty new to Laravel, but learning :) Thank you!

1 like

Please or to participate in this conversation.