简体   繁体   English

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

[英]Laravel - parameters in filter and routes

I have the following code: 我有以下代码:

filters.php filters.php

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

routes.php 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? 如果购物车为空,如何将用户重定向到"site/{$slug}" Can I use parameters in the filter.php or how can I send the "slug" to the filter? 是否可以在filter.php中使用参数,或者如何将“ slug”发送到过滤器?

Your issue is likely in your Route::group line. 您的问题很可能在Route::group行中。 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. 您在组中定义的路由仅在所有3个过滤器都通过后才有效,如果任何一个过滤器都失败,则会得到404。如果您想在过滤器失败时执行某些操作,则可以在路由文件并在控制器的构造函数或其他地方实现。

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);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM