Search code examples
phplaravelauthenticationsessiondashboard

How to redirect the user to dashboard if i remove the "/dashboard" from the port server in Laravel?


My port server is my login interface. * http://127.0.0.1:8000/* That is my login part, after entering my details it will redirect me to my dashboard http://127.0.0.1:8000/dashboard. But if I remove the /dashboard from the url it returns me back to login even when I am still in session and hasn't yet click the logout button. If I put the /dashboard again I will return to the dashboard because the user is still in session. I want to return to dashboard even I remove /dashboard. How to do that in Laravel?


Solution

    • Middleware can do this work for you. just follow
    1. Firstly, you have to create a middleware.
    php artisan make:middleware RedirectIfUserAuthenticated
    
    1. Register your middleware at kernel:
     protected $routeMiddleware = [
        ..............................
        'auth.backend' => Middleware\RedirectIfUserAuthenticated::class,
     ];
    
    1. Call your middleware at your routes or controller which you want to user authenticated can see after they're login.
    Route::group(['middleware' => ['auth.backend'], function () {
         // Add your routes except login route.
    }]);
    
    1. Let's added some codes into middleware that we have created: RedirectIfUserAuthenticated
    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Support\Facades\Auth;
    
    class RedirectIfUserAuthenticated
    {
        /**
         * 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()->check()) {
                return redirect()->to('/dashboard');
            }
    
            return $next($request);
        }
    }
     
    
    • Important: You can added middlware auth to your routes this will work as well if you don't want to create new one: Locat at: Middlewares/Authenticat.php and custom whatever your want.
    Route::group(['middleware' => ['auth'], function () {
         // Add your routes except login route.
    }]);
    

    Done !