【问题标题】:PHP - Routing with Parameters in LaravelPHP - 在 Laravel 中使用参数路由
【发布时间】:2013-01-15 05:07:04
【问题描述】:

我正在尝试使用 Laravel 创建一个 RESTful API。

在我的routes.php

Route::get('/accounts/(:any?)', array('as'=>'account_index', 'uses'=>'accounts@index'));

我的控制器:

class Accounts_Controller extends Base_Controller {
public $restful = true;

public function get_index($id = null) {
    if(!$id)
        return Response::json(Account::all());
    return Response::json(Account::find($id));
}

当我尝试任何请求 accounts/## 时,我得到 404 响应,但 accounts 工作正常。当我将路线更改为不是accounts 时,例如:

Route::get('/accts/(:any?)'

我的路由按预期工作,除此之外,发送到accounts 的请求仍然可以正常工作。是不是因为我使用get_index 作为我的函数名称,所以它恢复为使用标准的http://localhost/controller/method/arguments

编辑我有控制器被自动检测:

Route::controller(Controller::detect());

【问题讨论】:

  • 你的其他路线是什么?你在使用 Route::controller 吗?如果是这样,则需要在您的其他路线之后定义。
  • 我定义的唯一其他路由是Laravel自带的默认主页,并且Controllers正在注册Route::controller(Controller::detect());

标签: php laravel


【解决方案1】:

定义路由时,定义这些路由的顺序很重要。 Laravel 使用正则表达式将请求的 URI 与这些模式进行匹配,并且使用第一个匹配的 URI,无需进一步处理。

Route::controller('accounts')accounts/(:any?)/(:any?)/(:any?) 等有效匹配。如果您要测试 url accounts/index/12 您会得到预期的结果。

Route::get('/accounts/(:any?)', array('as'=>'account_index', 'uses'=>'accounts@index'));
Route::controller( Controller::detect() );

希望这会有所帮助。

【讨论】:

  • 这应该成为问题下的评论。如果你觉得最后一句话回答了原问题,我建议详细说明,并将最初的问题移至 cmets。
  • 很抱歉,乔治,这是一个评论,我没有注意。从actaeon获得更多信息后,这是一个真正的答案。
  • 啊,所以注册控制器实际上强制执行http://localhost/controller/method/arguments 方案。如果我只想手动进行路由,我不应该输入Controller:detect()。我把线拿出来了。感谢您的帮助!
猜你喜欢
  • 2019-11-07
  • 2016-02-14
  • 2016-03-05
  • 2021-02-04
  • 2017-10-01
  • 2014-10-26
  • 2017-10-07
  • 1970-01-01
  • 2021-05-11
相关资源
最近更新 更多