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:
-
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 StoreIntendedUrlIn 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); } } -
Register Middleware: Register the middleware in
app/Http/Kernel.php:protected $middlewareGroups = [ 'web' => [ // Other middleware \App\Http\Middleware\StoreIntendedUrl::class, ], ]; -
Customize Redirects in Fortify: Customize the redirect behavior in
FortifyServiceProvider. Openapp/Providers/FortifyServiceProvider.phpand modify theredirectsfor 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')); }); } -
Update Jetstream Configuration: Ensure that Jetstream is configured to use Fortify's redirect logic. In
config/jetstream.php, set thehomeroute 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.