View depending on middleware

Published 2 years ago by JhumanJ

Hello everybody, my name is Julien, and i'm new to Laracasts.

I want the view returned on my home page (route '/') to depend on the middleware.

Route::group(['middleware' => 'auth'], function () {

    Route::get('/', function () {
        return view('home');
    });

   ....

});

Route::group(['middleware' => 'guest'], function () {

    Route::get('/', function () {
        return view('welcome');
    });
    
.....
}); 

I tried this but it doesn't work... I also tried to use the Authcontroller to handle this, but it doesn't work either... Do you have any ideas? Thanks

Julien

Best Answer (As Selected By JhumanJ)
InaniELHoussain

what about this

Route::get('/', function () {
    if (Auth::check()) {
             return view('home');
    } else {
        // not logged-in
        return view('welcome');
    }
});
RomainLanz

Hey @JhumanJ and welcome to Laracasts!

Your code looks perfectly fine. Did you get any error or it is just always redirecting to one view?

JhumanJ

Hello @RomainLanz and thanks for your quick reply!

Ok, so basically when I do that with my routes, it's like if the auth middleware "takes" over the guest one. I configured the auth middleware to redirect to the login page, if somebody tries to access to any logged functionality/pages. And because of that, when guests tries to access the home page (not logged), it automatically redirects to the login page...

I don't know if I'm really clear do you understand?

primordial

Never tried this approach but would it not always return the "home" view?

An alternative approach maybe two routes, one for authenticated users. For example; a Home page and a Dashboard. Then use middleware to redirect any unauthenticated user.

I live and learn.

JhumanJ

Hey @primordial

In my first message I reversed the order of auth routes and guest routes (compared to my code), but yeah, it always return the 'home' (and so to the login page if not logged).

So isn't there a way to have both page, dashboard and home page use the same url/route?

InaniELHoussain

what about this

Route::get('/', function () {
    if (Auth::check()) {
             return view('home');
    } else {
        // not logged-in
        return view('welcome');
    }
});
JhumanJ

Yep it perfectly does the work thanks!

Please sign in or create an account to participate in this conversation.