How to use route / (index) twice for login and logout?

I am working on a Laravel project. The project has an open (non-authenticated section of the site) and authenticated section (admin).

I am trying to use / route to display a publicly accessible public view, and then during authentication I would like the same / route to display an authenticated admin view.

This is the 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 log out and try to access the / route, Public Control (Public.home) is considered as an authenticated route (which is placed under the auth middleware in the route group above).

The middleware tool is configured to redirect to / when accessing any secure (authenticated) routes.

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);
    }
}

Laravel 5.2.

+4
1

.

('/') auth , , , .

- :

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');
    }
}

. .

('home'), if, , .

- :

@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
+3

Source: https://habr.com/ru/post/1648903/


All Articles