Laravel:如何从路由跳转后的页面获取传递的数据?
/players/create?3 Hey there! Let's break this down and get your data properly accessible in the target page.
First, let's clarify why your URL ended up as /players/create?3: When you called route('players.create', $post->id), your players.create route doesn't have a defined route parameter (like {post}), so Laravel appended the ID as a query string—but without a key, hence the odd ?3 format. This works, but it's not the most clean approach. Let's cover both how to retrieve the data as-is, and how to improve the parameter passing for better clarity.
Option 1: Retrieve the "unkeyed" query value (current setup)
Since your URL has a query string without a key (?3), you can grab this value by accessing the raw query parameters array and picking the first element:
// In your PlayersController's create method $postId = array_values(request()->query())[0]; // Or use Collection for safer handling (works even if no params exist) $postId = collect(request()->query())->first();
This will get you the 3 value from the URL. That said, this approach is not ideal because it's unclear what the value represents at a glance.
Option 2: Improve parameter passing (recommended)
A better practice is to pass the ID with a named query parameter, so your URL becomes /players/create?post_id=3. Modify your route call to pass an associative array:
<a href="{{ route('players.create', ['post_id' => $post->id]) }}" class="btn btn-primary">
Then retrieving the data in your controller is straightforward and readable:
// In PlayersController@create // Using the request helper $postId = request()->query('post_id'); // Or if you type-hint the Request instance use Illuminate\Http\Request; public function create(Request $request) { $postId = $request->post_id; // Or explicitly fetch the query parameter $postId = $request->query('post_id'); }
Option 3: Use Route Parameters (cleanest approach, if applicable)
If this post_id is a required part of your route logic, you can define a route parameter instead of using query strings. Update your route in routes/web.php:
Route::get('/players/create/{post}', [PlayersController::class, 'create'])->name('players.create');
Your link will now generate a cleaner URL: /players/create/3. You can retrieve the ID directly in your controller method—even use Laravel's Route Model Binding to get the full Post instance:
// Basic ID retrieval public function create($postId) { // Use $postId here } // Route Model Binding to get the full Post model public function create(App\Models\Post $post) { // $post is the complete Post model matching the ID }
内容的提问来源于stack exchange,提问作者Johnny Nicodin

