PHP-Laravel中带参数的路由 [英] PHP - Routing with Parameters in Laravel

查看:466
本文介绍了PHP-Laravel中带参数的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Laravel创建RESTful API.

I'm trying to create a RESTful API using Laravel.

在我的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的东西时:

I get 404 responses when I try any request accounts/##, but accounts works just fine. When I change my route to something that isn't accounts like:

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

我的路由按预期工作,并且最重要的是,发送到accounts的请求仍然正常工作.是因为我在函数名称中使用了get_index,所以它恢复为使用标准的http://localhost/controller/method/arguments?

My routing works as expected, and on top of that requests sent to accounts still work as well. 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?

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

EDIT I have controllers being auto-detected:

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

推荐答案

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

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.

Route::controller('accounts')有效地匹配了accounts/(:any?)/(:any?)/(:any?)等.如果您要测试网址accounts/index/12,您将获得预期的结果.

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::get('/accounts/(:any?)', array('as'=>'account_index', 'uses'=>'accounts@index'));
Route::controller( Controller::detect() );

希望这会有所帮助.

这篇关于PHP-Laravel中带参数的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆