Steve Kutcher Steve Kutcher - 4 months ago 7
PHP Question

How do I use the / (index) route twice for both logged in and logged out?

I'm working on a Laravel project. The project has a public (non authenticated section of the site) and an authenticated section (admin).

I am attempting to use the / route to display a public homepage view, and then when authenticated I'd like the same / route to display the admin authenticated view.

This is the attempted code:

routes.php

Route::auth();

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

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

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


Problem
When I am logged out and try to access the / route, the Public controller (Public.home) is considered as an authenticated route (as placed under the 'auth' middleware in the route group above).

The middleware auth is set to redirect to / when any protected (authenticated) routes are accessed.

Authenticate.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;

class Authenticate
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (Auth::guard($guard)->guest()) {
if ($request->ajax() || $request->wantsJson()) {
return response('Unauthorized.', 401);
}

return redirect()->guest('/');
}

return $next($request);
}
}


I am using Laravel 5.2.

Answer

There's a couple of ways to get around this.

The first would be to exclude your ('/') route from theauth` middleware and write your own to check if they are logged in or not and return the appropriate view based on that.

Something like this would do the trick:

public function handle($request, Closure $next)
{
    if (Auth::check())
    {
        //The user is logged in
        return view('Authenticated.home');
    }

    else
    {
        //The user is not logged in
        return view('Public.home');
    }
}

Fore more info on writing your own middleware, see the docs for this.

Alternatively you can just create the one view ('home') and then use and if statement to check if they are logged in or not.

Something like this would do the trick:

@if (Auth::check())
    //User is logged in
    //HTML that we want to show to authenticated user
@else
    //User is not logged in
    //HTML that we want to show to general public
@endif
Comments