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
    
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本