dongren9739 2014-09-05 19:12
浏览 95
已采纳

有没有办法在Controller Action之前访问Laravel Route参数?

I'm writing an api using Laravel 4 where a portion of the URL will determine what database the data will be pulled from. There will be a large number of databases each with the same schema, for example:

mystuff_arizona
mystuff_florida
...

This is a given (a requirement I have to work with).

So the following urls (to 'show' a resource by id)...

www.mysite.com/arizona/api/v1/items/9

www.mysite.com/florida/api/v1/items/9

can use the same controller, but I need to add some code in Laravel (in a base controller or 'before' function) to setup the correct database connection depending on the URL.

I've been working with something like this:

Route::group(['prefix' => '{state}/api'], function($state=null)
{
    Route::group(['prefix' => 'v1'], function()
    {
        Route::resource('items', 'ItemsController');
    });
});

But, in my controller, I need to add the $state parameter to the show() method, although I'm not going to use it there.

//public function show($state,$id) // <<-- this works
public function show($id) // <<-- this fails
{
    $record = Item::findOrFail($id);
    return Response::json( $record->toArray()) );
}

My questions are:

1) Is there a way to access the $state parameter from the route before 'show' is called (either in the base controller or in the Controller's 'before' method)?

2) Is there a way to tell show() and update() resource methods to forget about the $state parameter?

I could use native PHP to do this I'm sure, but I'm wondering if Laravel has some pre-built functionality to offer here.

  • 写回答

1条回答 默认 最新

  • doudun5009 2014-09-05 19:25
    关注

    You could use a route filter

    Route::filter('name', function()
    {
        $routeParameters = Route::getCurrentRoute()->getParameters();
        $state = $routeParameters['state'];
        Route::getCurrentRoute()->setParameters($routeParameters);
    
        // Do something with $state
    
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习或深度学习问题?困扰了我一个世纪,晚来天欲雪,能饮一杯无?
  • ¥15 c语言数据结构高铁订票系统
  • ¥15 关于wkernell.PDB加载的问题,如何解决?(语言-c#|开发工具-vscode)
  • ¥15 (标签-STM32|关键词-智能小车)
  • ¥20 关于#stm32#的问题,请各位专家解答!
  • ¥15 (标签-python)
  • ¥20 搭建awx,试了很多版本都有错
  • ¥15 java corba的客户端该如何指定使用本地某个固定IP去连接服务端?
  • ¥15 activiti工作流问题,求解答
  • ¥15 有人写过RPA后台管理系统么?