简体   繁体   English

PHP-Laravel中带参数的路由

[英]PHP - Routing with Parameters in Laravel

I'm trying to create a RESTful API using Laravel. 我正在尝试使用Laravel创建RESTful API。

In my routes.php : 在我的routes.php

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

My controller: 我的控制器:

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));
}

I get 404 responses when I try any request accounts/## , but accounts works just fine. 尝试任何请求accounts/## ,我都会收到404响应,但是accounts工作正常。 When I change my route to something that isn't accounts like: 当我将路线更改为非以下accounts

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

My routing works as expected, and on top of that requests sent to accounts still work as well. 我的路由可以按预期工作,并且最重要的是,发送到accounts请求仍然可以正常工作。 Is it because I'm using get_index for my function name, so that it reverts to using the standard http://localhost/controller/method/arguments ? 是因为我将get_index用作函数名,以便它恢复为使用标准的http://localhost/controller/method/arguments吗?

EDIT I have controllers being auto-detected: 编辑我有控制器被自动检测到:

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

When you define routes, the order in which these routes are defined matters. 定义路由时,定义这些路由的顺序很重要。 Laravel uses regular expressions to match the requested URI against these patterns, and the first one to match is used with no further processing. Laravel使用正则表达式将请求的URI与这些模式进行匹配,并且使用第一个要匹配的URI而不进行进一步处理。

Route::controller('accounts') is effectively matching accounts/(:any?)/(:any?)/(:any?) etc. If you were to test the url accounts/index/12 You would get the expected result. 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() );

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM