lukeboy_2002's avatar

how to redirect back after login or registration laravel 11

Hi,

I want to redirect user back to the url they came from when they have to login or register instead of the default route in fortify.php For the authentication I use Jetstream.

Can this be changed?

0 likes
1 reply
LaryAI's avatar
Level 58

Certainly! To redirect users back to the URL they came from after login or registration in Laravel 11 using Jetstream, you can customize the authentication process. Here’s how you can achieve this:

  1. Middleware to Store Intended URL: Create a middleware to store the intended URL before redirecting to the login or registration page.

    php artisan make:middleware StoreIntendedUrl
    

    In the generated middleware (app/Http/Middleware/StoreIntendedUrl.php), add the following code:

    namespace App\Http\Middleware;
    
    use Closure;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Session;
    
    class StoreIntendedUrl
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle(Request $request, Closure $next)
        {
            if ($request->is('login') || $request->is('register')) {
                Session::put('url.intended', url()->previous());
            }
    
            return $next($request);
        }
    }
    
  2. Register Middleware: Register the middleware in app/Http/Kernel.php:

    protected $middlewareGroups = [
        'web' => [
            // Other middleware
            \App\Http\Middleware\StoreIntendedUrl::class,
        ],
    ];
    
  3. Customize Redirects in Fortify: Customize the redirect behavior in FortifyServiceProvider. Open app/Providers/FortifyServiceProvider.php and modify the redirects for login and registration:

    use Illuminate\Support\Facades\Session;
    
    public function boot()
    {
        // Other Fortify configurations
    
        Fortify::authenticateUsing(function (Request $request) {
            // Your custom authentication logic
        });
    
        Fortify::loginView(function () {
            return view('auth.login');
        });
    
        Fortify::registerView(function () {
            return view('auth.register');
        });
    
        Fortify::redirects(function ($request) {
            return Session::pull('url.intended', config('fortify.home'));
        });
    }
    
  4. Update Jetstream Configuration: Ensure that Jetstream is configured to use Fortify's redirect logic. In config/jetstream.php, set the home route to the default Fortify home route:

    'home' => config('fortify.home'),
    

By following these steps, you will store the intended URL before redirecting to the login or registration page and then redirect the user back to that URL after they have successfully logged in or registered.

Please or to participate in this conversation.