【问题标题】:Accessing route parameter in view with Laravel 4使用 Laravel 4 访问视图中的路由参数
【发布时间】:2014-03-25 04:04:52
【问题描述】:

我的路线设置如下:

Route::match(array('GET', 'POST'), '/reset-password/{code}', array('as' => 'reset-password-confirm', 'uses' => 'UserController@resetPasswordConfirm'));

在我的控制器中,我将路由参数传递给我的操作,如下所示:

public function resetPasswordConfirm($code)
{
    // ...
}

然后我可以在我的控制器中正常使用$code

在我看来,我正在构建一个 POST 到同一控制器操作的表单,我需要以某种方式将 $code 放入视图中,以便它构造正确的表单操作。目前我有这个:

{{ Form::open(array('route' => array('reset-password-confirm'))) }}

因为我没有提供$code 路由参数,所以表单是这样打开的:

<form method="POST" action="http://site.dev/reset-password/%7Bcode%7D" accept-charset="UTF-8">

显然,这与我定义的路由不匹配(​​由于{code} 不存在)并且路由匹配失败。我需要以某种方式将路由参数放入我的视图中,以便我可以将它与Form::open() 一起使用。我试过这样做:

{{ Form::open(array('route' => array('reset-password-confirm', $code))) }}

但这只会引发一个异常,说 $code 未定义。

【问题讨论】:

    标签: php laravel laravel-4 url-routing


    【解决方案1】:

    parameter 发送到视图的正确方法是:

    return View::make('viewname')->with('code', $code);
    

    或者你可以使用:

    return View::make('yourview', compact('code'));
    

    因此,$code 将在您的视图中可用,您可以在表单中使用它,但您也可以使用以下方法在视图中访问 parameter

    // Laravel - Latest (use any one)
    Route::Input('code');
    Route::current()->getParameter('code');
    Route::getCurrentRoute()->getParameter('code');
    
    // Laravel - 4.0
    Route::getCurrentRoute()->getParameter('code');
    

    【讨论】:

    • 我一直在互联网上寻找这些信息。这是我在其中找到的唯一线程。谢谢。
    • 欢迎您。很高兴帮助你:-)
    【解决方案2】:

    也许我不清楚你的问题,但你可以定期将它传递给视图(就像你传递任何其他变量一样,即)

    public function resetPasswordConfirm($code)
    {
        return View::make('yourview')->with('code', $code);
    }
    

    并且在视图中 $code 将被定义:

    {{ Form::open(array('route' => array('reset-password-confirm', $code))) }}
    

    直接从 Request 对象在您的视图中捕获它:

    {{ Form::open(array('route' => array('reset-password-confirm', Request::segment(2) ))) }}
    

    顺便说一句,我想你也可以这样写你的路线:

    Route::any('reset-password/{code}', array('as' => 'reset-password-confirm', 'uses' => 'UserController@resetPasswordConfirm'));
    

    【讨论】:

      猜你喜欢
      • 2014-08-10
      • 2013-11-24
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      • 2014-08-29
      • 1970-01-01
      • 2013-10-16
      • 2014-10-13
      相关资源
      最近更新 更多