How to apply multiple filters on Laravel 4 route group?

筅森魡賤 提交于 2019-12-30 04:34:06

问题


Is it possible to add multiple filters on a group route in Laravel 4?

I have 2 authentification methods for an API centric application. One with standard authentification (filter "auth" for website), one with token (filter "auth.token" for mobile app).

<?php
    Route::group(array('prefix' => 'api/'), function() {
        #Custom routes here
    });
?>

Ideally I'd like that if one of the two filters pass, group is accessible.


回答1:


You can:

Route::group(['before' => 'auth|csrf'], function()
{
     //
});

However if you want to make it accesible if either of the filters passes, you'd have to write a little bit more (in filters.php):

function csrfFilter()
{
    if (Session::token() != Input::get('_token'))
    {
        throw new Illuminate\Session\TokenMismatchException;
    }
}
function authFilter()
{
    if (Auth::guest()) return Redirect::guest('login');
}

Route::filter('csrf-or-auth', function () 
{
    $value = call_user_func('csrfFilter');
    if ($value) return $value;
    else return call_user_func('authFilter');
});

In routes.php

Route::group(['before' => 'csrf-or-auth'], function()
{
     //
});

Remember you have to return nothing when the filter passes. I hope this helps you!




回答2:


You can do that with laravel

Route::group(array('prefix' => 'api/', 'before' => 'filter1|filter2'), function()
{
    Route::get('api1', function()
    {
        // Has Filter1 and filter2
    });

    Route::get('api2', function()
    {
        // Has filter1 and filter2
    });
});

check the documentation for more details



来源:https://stackoverflow.com/questions/23224096/how-to-apply-multiple-filters-on-laravel-4-route-group

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!