【问题标题】:Passing form values with RESTful routing in Laravel 4在 Laravel 4 中使用 RESTful 路由传递表单值
【发布时间】:2014-11-17 04:14:14
【问题描述】:

我已经设置了嵌套的 RESTful 资源路由,如下所示:

Route::group(array('prefix'=>'opening-hours'), function(){
    Route::resource('library', 'LibraryController');
    Route::resource('library.interval', 'LibraryIntervalController');
});

我有一个刀片表单,它有一个选择下拉菜单,其中包含从数据库填充的选项,如下所示:

{{ Form::open(array('route' => 'opening-hours.library.show', 'method' => 'GET')) }}
    <legend>Select a library to edit</legend>
    <div class="form-group">
        <label for="">Please select a library to modify its opening hours:</label>
        <select class="form-control" name="id" required>
        @foreach ($library_options as $id => $name)
          <option value="{{ $id }}">{{ $name }}</option>
        @endforeach
        </select>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
{{ Form::close() }}

表单提交到命名路由:

opening-hours.library.show

路由本身有效,但我有几个关于物流的问题(我对如何使用路由有点困惑):

  • 如果我将表单设置为 'GET' 请求(GET/HEAD 开放时间/图书馆/{图书馆} => opening-hours.library.show),因为对应的 POST 路由没有 存在
  • 如何将用户选择的 $id 传递给控制器​​ show($id) 方法?
  • 当我提交表单时,它会转到 URI “../开放时间/图书馆/%7Blibrary%7D?id=3”。所以如果用户选择 id=3 的库,如何使 URI “../opening-hours/library/3”?

这是我的库控制器显示方法:

/**
 * Display the specifed library.
 *
 * @param  int  $id
 * @return Response
 */
public function show($id)
{
    //
    return "This is a library with id: " . $id . "!";
}

当我提交表单时,会显示以下内容:

这是一个 id 为 {library} 的库!

当然,我希望它显示:

这是一个 id 为 3 的库!

我显然不了解 REST 或 Laravel 或两者在这里如何工作的关键。任何指点都将不胜感激,我花了一天的时间来解决这个问题!

非常感谢

【问题讨论】:

    标签: php forms rest laravel-4 laravel-routing


    【解决方案1】:

    尝试使用

    $id = Input::get('id');
    

    Documentation

    我还建议使用提供的表单助手:

    echo Form::select('size', array('L' => 'Large', 'S' => 'Small'));
    

    Documentation

    【讨论】:

    • 感谢 - Input::get('id') 确实允许我访问 $id 变量,但没有解决生成 URI 的问题。我通过使用锚点而不是表单解决了我的问题
    【解决方案2】:

    写出问题似乎有助于我想出解决方案。使用表单发送“GET”请求似乎很愚蠢,所以我想(bing!)为什么不将 URI 构造为锚标记 href 属性。所以我没有使用表格,而是这样做了:

    @foreach( $library_options as $id => $name )    
        <a class="btn btn-primary" href="{{ URL::to('opening-hours/library/' . $id) }}">Edit {{ $name }}</a>
    @endforeach
    

    这解决了不可靠的 URI 问题,并且 id 可以直接从 RESTful 控制器方法获得,如下所示:

    public function show($id)
    {
        return "This is a library with id: " . $id . "!";
    }
    

    【讨论】:

      猜你喜欢
      • 2013-05-22
      • 2014-09-05
      • 1970-01-01
      • 2016-02-27
      • 2014-01-06
      • 2014-03-08
      • 2014-06-08
      • 1970-01-01
      • 2017-08-04
      相关资源
      最近更新 更多