如何在 Laravel 中对指定的控制器操作进行过滤

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18554691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:21:55  来源:igfitidea点击:

How to do filter on specified controller action in Laravel

phplaravel

提问by Chan

I have CartController route filter seems only can bind on controller or get, can I do the auth filter on "action"?

我有 CartController 路由过滤器似乎只能绑定在控制器上或获取,我可以对“动作”进行身份验证过滤器吗?

for example:

例如:

<?php

CartController extends BaseController {

    public function getIndex() {
        // not need filter
    }

    public function getList()
    {
        // not need filter
    }

    public function getCheck()
    {
        // need to filter
    }

}

回答by Sashel Niles Gruber

You can set the BaseController beforeFilter() Action in your Class constructor and pass the Actions you want filtered as an 'only' keyed Array as the second Argument.

您可以在 Class 构造函数中设置 BaseController beforeFilter() Action 并将要过滤的 Actions 作为“唯一”键控数组作为第二个参数传递。

$this->beforeFilter('filtername', 
                    array('only' => array('fooAction', 'barAction')));

Using your example code:

使用您的示例代码:

<?php

CartController extends BaseController {

    public function __construct() {

        $this->beforeFilter('filtername', array('only' =>
                            array('getCheck')));
    }

    public function getIndex() {
        // not need filter
    }

    public function getList()
    {
        // not need filter
    }

    public function getCheck()
    {
        // need to filter
    }

}

Source: Laravel Docs: Controller Filter

来源:Laravel 文档:控制器过滤器

回答by Herman Tran

It seems you want to mix RESTful and normal methods (get/post vs action) together in the same controller, and at least in Laravel 3 this couldn't be done.

似乎您想在同一个控制器中将 RESTful 和普通方法(get/post vs action)混合在一起,至少在 Laravel 3 中这是无法做到的。

For filtering, you can look into controller filterswhere you can specific the auth filter for specific methods or go the other way and exclude certain methods from the filter.

对于过滤,您可以查看控制器过滤器,您可以在其中为特定方法指定 auth 过滤器,或者以其他方式从过滤器中排除某些方法。

回答by fideloper

You can call the filter in the method you need it in.

您可以在需要的方法中调用过滤器。

See the documentation hereto see what that looks like in code.

请参阅此处的文档以查看代码中的内容。

 $this->beforeFilter('my-filter-name');

回答by nsbucky

I had a similar issue with a resource controller and was able to do this:

我在资源控制器上遇到了类似的问题,并且能够做到这一点:

$this->beforeFilter('admin', [ 'except' => ['index','show'] ]);