dongyinju5977 2014-10-13 11:25
浏览 112
已采纳

Laravel - 过滤器和路由中的参数

I have the following code:

filters.php

Route::filter('empty_cart', function () {
    if (empty(Cart::contents()) || Cart::totalItems() == 0) {
        return Redirect::to('');
    }
});  

routes.php

Route::group(array('before' => 'csrf','before' => 'detectLang','before' => 'empty_cart'), function () {
    Route::get('site/{slug}/cart', array('uses' => 'CartController@getCart'));
    Route::get('site/{slug}/cart/billing', array('uses' => 'CartController@getBilling'));
    Route::get('site/{slug}/login', array('uses' => 'UsersController@getLoginForm'));
});  

How can I redirect the user to the "site/{$slug}" if the cart is empty? Can I use parameters in the filter.php or how can I send the "slug" to the filter?

  • 写回答

1条回答 默认 最新

  • dtdb99743 2014-10-13 11:38
    关注

    Your issue is likely in your Route::group line. You are passing an array of filters to run but giving each individual item the same key. You should split each before filter with a pipe |:

    Route::group(array('before' => 'csrf|detectLang|empty_cart'), function () {
        // Your routes here
    }
    

    The routes you define within the group will only be valid when all 3 filters are passed, if any of the filters fail, you will get a 404. If you would like to implement certain action when a filter fails you can remove this filter in the routes file and implement it on the controller's constructor or elsewhere.

    Alternatively, you could try adding another route after this group, that doesn't apply the filters such that any requests that don't match the filtered routes will be caught by this event. You could then put your redirect in place.

    Route::group(array('before' => 'csrf|detectLang|empty_cart'), function () {
        Route::get('site/{slug}/cart', array('uses' => 'CartController@getCart'));
    }
    
    Route::get('site/{slug}/cart', 'YourController@yourAction');
    // OR
    Route::get('site/{slug}/cart', function($slug){
        return Redirect::to('/'. $slug);
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作