Laravel - parameters in filter and routes

Marek123

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?

Jonathon

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related