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

查看:17
本文介绍了如何在 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 IlluminateSessionTokenMismatchException;
    }
}
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天全站免登陆