Laravel显示参数名称而不是值(在路由中使用可选参数时)

时间:2016-09-26 12:46:40

标签: php google-maps laravel routing laravel-5.1

我有一个表单,用户可以在其中输入起始位置,在提交时,他将转到以此位置为中心的地图。他也可以跳过这一步直接进入地图。 (这是跳过整个背景故事的简化版)

这是第一段代码,当用户使用表单时,它将从表单中获取起始位置并重定向到地图:(不要介意计划变量,它始终是'拥有&# 39;为了本案的目的)

Route::post('InitiateUserTrip', ['as' => 'InitiateUserTrip', function(WelcomeFormRequest $request) 
{
    if (Input::get('planning') == 'own') {
        return Redirect::route('Map',array('startLocation', Input::get('startLocation')));
    } else {
      return view('welcome');
    }
} ]);

这是地图路线,startLocation是可选的,如上所述。 (API密钥将是我的个人API密钥。)我在这里看到的是调试条显示' startLocation'而不是参数的值。 (名称而不是值)

Route::get('Map/{startLocation?}', ['as' => 'Map', function($startLocation = null)
{
    $map = new Map('API KEY',$startLocation,'GMainMap');    
    $googleMap = $map->getMap();
    $node = new Node();
    $node->loadBySelection('ALL');
    $nodes = $node->getNodes();
    \Debugbar::info("Map: " . $startLocation);
    return View::make('map')->with('map', $googleMap)
                            ->with('nodes',$nodes)
                            ->with('startLocation',$startLocation);
}]);

我开始玩网址,看看发生了什么。 假设用户输入了迈阿密'作为startLocation,这将导致以下URL:

http://laravel.dev/Map/startLocation?Miami => Debugbar将显示' startLocation'

当我自己修改网址时 http://laravel.dev/Map/Miami =>调试栏将显示“迈阿密”

不仅Debugbar会显示错误的内容。我尝试基于此变量进行地理编码,但由于它将内容视为' startLocation'同样。

我或许可以通过创建两个路径来解决这个问题,一个路由,一个路径没有参数,但我想我只是遗漏了一些明显的东西。

2 个答案:

答案 0 :(得分:0)

您的路线按预期工作。请注意, {startLocation?} 不是网址的一部分,而是由参数的实际值替换的占位符。

因此,路由:: get(' Map / {startLocation?}',...); 路由表示 startLocation 参数值是 Map / 之后的任何值。因此,如果您转到 Map / startLocation?Miami startLocation 字符串将被视为参数的值。

同时提供 / Map / Map / startLocation?迈阿密网址的最简单方法是定义2条路线:

Route::get('Map', ...);
Route::get('Map/startLocation?{startLocation}', ...);

答案 1 :(得分:0)

您的路线呼叫中有错误

Redirect::route('Map',array('startLocation', Input::get('startLocation')));

应该是这样的:

Redirect::route('Map',array(Input::get('startLocation')));

您不需要在路由调用中指定键,该数组将根据它们在数组中的位置与给定路径中的参数配对,例如。数组中的第一项到路径中的第一个参数,数组中的第二项到路径中的第二个参数等。