Laravel:如何将注册页GET参数传递至自定义重定向URL
Hey there! Let's clear up your confusion about handling post-registration redirects with preserved GET parameters in Laravel.
First off, you don't need to call redirectTo() manually in your create() method — Laravel's built-in registration flow handles the redirect automatically using the logic from the RedirectsUsers trait. Here's the proper way to implement this:
Step 1: Override the redirectTo method in your RegisterController
The RedirectsUsers trait lets redirectTo be either a property or a method. When you define it as a method, Laravel automatically passes the incoming $request to it, so you can easily grab the GET parameters directly from there.
Add this code to your Auth\RegisterController:
use Illuminate\Http\Request; // ... protected function redirectTo(Request $request) { // Grab the specific parameters you want to retain (use $request->query() to get all) $preservedParams = $request->only(['param1', 'param2']); // Redirect to your target route — the route helper auto-appends query params from the array return route('example', $preservedParams); }
Why your original approach wasn't ideal
- No need to call
redirectTo()increate(): The registration controller'sregister()method (from theRegistersUserstrait) already handles redirecting by callingredirectPath(), which checks for your customredirectTomethod/property automatically. - Manually building the URL with query strings (
?param1=...) is unnecessary — theroute()helper will append parameters correctly when you pass an array of key-value pairs as the second argument.
A quick edge case tip
If some parameters might be optional (not present in the original request), use $request->get('param1', '') to set a default empty value, or filter out empty entries from $preservedParams if you want to skip missing parameters entirely.
That's all! With this setup, after a user finishes registration, they'll be redirected to your example route with all the GET parameters they arrived at the registration page with intact.
内容的提问来源于stack exchange,提问作者eskimo

