phplaravellaravel-authenticationlaravel-12

Laravel V12 authentication redirects to /home instead of custom URL


I am using built-in authentication for login and registration with the following command:

php artisan ui bootstrap --auth

Now, the problem is that I am already logged into my site. When I open another tab and visit the login URL:

https://localhost/v12-world/login

It redirects me to:

https://localhost/v12-world/home

But I want to be redirected to:


https://localhost/v12-world/admin/cities 

I have already added this redirection in the LoginController.

Still having issue...

I modified the LoginController to change the redirection after login. However, even after making these changes, when I visit the login URL while already logged in, it still redirects to /home instead of /admin/cities.

I expected the system to detect that I am already logged in and directly redirect me to /admin/cities instead of /home.

LoginController :

<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/admin/cities';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
        $this->middleware('auth')->only('logout');
    }
}

Solution

  • For laravel 12, you can add the following in bootstrap/app.php:

    <?php
    
    use Illuminate\Foundation\Application;
    use Illuminate\Foundation\Configuration\Exceptions;
    use Illuminate\Foundation\Configuration\Middleware;
    
    return Application::configure(basePath: dirname(__DIR__))
        ->withRouting(
            web: __DIR__.'/../routes/web.php',
            commands: __DIR__.'/../routes/console.php',
            health: '/up',
        )
        ->withMiddleware(function (Middleware $middleware) {
            $middleware->redirectUsersTo('/admin/cities'); // add this
        })
        ->withExceptions(function (Exceptions $exceptions) {
            //
        })->create();
    

    You can check from this page here.