【问题标题】:resource controller, pass multiple parameters using AJAX资源控制器,使用 AJAX 传递多个参数
【发布时间】:2014-01-11 05:05:23
【问题描述】:

我第一次使用 laravel 创建一个 API,以便使用 AJAX 从 angular.js 单页应用程序访问。我不知道如何配置控制器和 URL 以将多个参数传递给任何方法

如下为我的 API 组配置路由

Route::group(array('prefix' => 'api/v1'), function(){
    Route::resource('event', 'EventController');    
});

EventController 方法都按文档记录工作,但是,我需要发送开始和结束日期作为参数来检索我的事件。

我还将missingMethod($parameters = array()) 放在控制器中,但从来没有运气让它触发

我尝试添加一个额外的参数来显示方法function show($start, $end),但无法弄清楚 AJAX URL 以使其工作。 尝试了多种方法:

/myapp/api/v1/event/param1/param2
/myapp/api/v1/event/param1,param2
 /* hoping missingMethod($parameters = array()) might get this one*/
/myapp/api/v1/event/[param1,param2] 

在大多数情况下,大多数尝试都会抛出 show 缺少第二个参数的异常。

我最终决定使用常规查询字符串并在我的 index() 函数中测试 Input::get()

/myapp/api/v1/event?param1=1&param2=2

我还尝试了几种方法在注册资源之前使用通配符添加Route::get('/event'),但均无济于事。

我想有一种相对简单的方法可以让资源控制器方法有多个参数,如果没有,如何配置 HTTP 请求以便missingMethod 接收数组?

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    您可以在resource 上方添加该特定路由(我假设您使用GET 处理您的ajax 请求):

    Route::group(array('prefix' => 'api/v1'), function(){
        Route::get('event/{start}/{end}', 'EventController@index');
        Route::resource('event', 'EventController');    
    });
    

    在您的控制器中,使您的参数成为可选参数,这样您就可以对两个路由使用相同的控制器操作,api/v1/eventapi/v1/event

    <?php
    
    class EventController extends BaseController {
    
        public function index($start = null, $end = null)
        {
            if (isset($start) && isset($end)) {
                return $this->eventsRepository->byDate($start, $end);
            }
    
            return $this->eventsRepository->all();
        }
    
    }
    

    如果您想更具体地了解 startend 通配符格式,可以使用 where:

    Route::get('event/{start}/{end}', 'EventController@index')
             ->where([
                'start' => 'regexp-here', 
                'end' => 'regexp-here'
               ]);
    

    【讨论】:

    • 我当然可以发誓我尝试过这种方法,但它有效....谢谢!我可以创建一个不是show,index,update 等的自定义方法,然后在Route 中的@myMethod 中使用它吗?
    • 是的,你可以用Route::get()绑定所有你想要的方法。也看看Route::controller(),也可能有用:laravel.com/docs/controllers#restful-controllers
    • 好的..谢谢。今天已经翻遍了这些文档。从字面上看,昨天刚开始使用 laravel,但已经有了你给我的工作。下一步将是找出存储库,但现在我的前端有很多工作要做,因为数据以我需要的方式流动
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 2015-04-03
    • 2015-08-11
    相关资源
    最近更新 更多