如何在Laravel 4路由组上应用多个过滤器? [英] How to apply multiple filters on Laravel 4 route group?

查看:51
本文介绍了如何在Laravel 4路由组上应用多个过滤器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Laravel 4的组路由中添加多个过滤器?

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

对于以API为中心的应用程序,我有2种身份验证方法. 一种带有标准身份验证(针对网站的过滤器"auth"),一种带有令牌(针对移动应用程序的过滤器"auth.token").

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.

推荐答案

您可以:

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

但是,如果要使任一过滤器通过都可以访问,则必须多写一些内容(在filters.php中):

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

在routes.php中

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!

这篇关于如何在Laravel 4路由组上应用多个过滤器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆