将 URL 中的变量传递给 Laravel 路由

Passing Variables in a URL to a Laravel Route

我想接收这样的 GET 请求:

people.php?name=Joe&age=24

为此,我定义了以下路线:

Route::get('people.php?name={username}&age={id}', array(
    'as' => 'people/username/age',
    'uses' => 'ExtraController@xfunction',
));

但这似乎不起作用。

如何定义这条路线?

Laravel 不支持查询字符串路由。

创建一个常规路由,然后从 Input 外观中提取查询字符串参数:

Route::get('people.php', array(
    'as' => 'people/username/age',
    'uses' => 'ExtraController@xfunction',
));
public function xfunction()
{
    $username = Input::get('name');
    $age      = Input::get('age');
}

正是约瑟夫上面所说的。但我想补充一点,所有查询都应始终在控制器方法中处理。我相信你知道,但最好的做法显然是永远不要在路由之外包含任何逻辑。

除了查询之外,您还可以使用 Laravel 中的可选变量。

因此,您可以使用 /test/{name?} 而不是 /test/?name=Jonathan,然后您可以将其视为 /test/ 或 /test/Jonathan,但在控制器方法中,您必须使用

public function ( $name = null; ) { dd($name); }