Laravel 5 中的过滤器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26373850/
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-08 16:46:56  来源:igfitidea点击:

Filters in Laravel 5

laravellaravel-5laravel-filters

提问by JoshuaDavid

How do we make filters in Laravel 5? Is the idea of filtersgoing away?

我们如何在 Laravel 5 中制作过滤器?过滤器的想法会消失吗?

回答by orrd

The short answer is no, route filters are notgoing away entirely in Laravel 5.0(despite some misleading information out there about this). The functionality still exists to let you use 'before' and 'after' filters on your routes if you would like. The "filters.php" file is no longer provided, but you can still define your filters somewhere else, probably most appropriately in the boot() function of Providers/RouteServiceProvider.php.

简短的回答是否定的,路由过滤器不会在 Laravel 5.0 中完全消失(尽管有一些关于此的误导性信息)。如果您愿意,该功能仍然存在,可让您在路线上使用“之前”和“之后”过滤器。不再提供“filters.php”文件,但您仍然可以在其他地方定义您的过滤器,可能最合适的是在 Providers/RouteServiceProvider.php 的 boot() 函数中。

However, middleware is now the preferred way to achieve the same functionality. See http://laravel.com/docs/master/middlewarefor info about how to use it.

但是,中间件现在是实现相同功能的首选方式。有关如何使用它的信息,请参阅http://laravel.com/docs/master/middleware

Middleware can be implemented to behave like either "before" or "after" filters. And it can be applied to all routes (called "global middleware"), or assigned to specific routes (by adding "'middleware' => 'auth'" for example to your route definitions in your routes.php file.

中间件可以实现为“之前”或“之后”过滤器。它可以应用于所有路由(称为“全局中间件”),或分配给特定路由(例如,通过将“'中间件' => 'auth'”添加到 routes.php 文件中的路由定义。

The only significant limitation of middleware is that it currently doesn't give you a way to pass parameters(as you can with filters). This means you can't do something like "requirePermission:admin" for example. There are currently two ways to deal with this limitation. You can instead just use a route filter instead, just as you did with Larvel 4.2. Or otherwise if you prefer using middleware, this feels like a bit of a hack, but you can pass parameters to the middleware by defining and retrieving custom values added to your route definition as explained at http://blog.elliothesp.co.uk/coding/passing-parameters-middleware-laravel-5/.

中间件的唯一重要限制是它目前没有为您提供传递参数的方法(就像您可以使用过滤器一样)。这意味着您不能执行诸如“requirePermission:admin”之类的操作。目前有两种方法可以处理此限制。您可以改为使用路由过滤器,就像您在 Larvel 4.2 中所做的那样。或者,如果您更喜欢使用中间件,这感觉有点像黑客,但您可以通过定义和检索添加到您的路由定义的自定义值将参数传递给中间件,如http://blog.elliothesp.co.uk 所述/coding/passing-parameters-middleware-laravel-5/

2015-05-29 Update:Middleware parametersare available starting with Laravel 5.1.

2015-05-29 更新:从 Laravel 5.1 开始提供中间件参数

2015-06-10 Update:Route filters have been deprecated in preference of middleware and will be removed entirely with the release of Laravel 5.2 in December 2015.

2015-06-10 更新:路由过滤器已被弃用,优先于中间件,并将在 2015 年 12 月发布的 Laravel 5.2 中完全删除。

回答by igaster

  1. Create a middleware with

    php artisan make:middleware class_name
    
  2. Create a short-hand key in your app/Providers/RouteServiceProvider.php :

    protected $middleware = [
      // ....
      'shortName'  => 'App\Http\Middleware\class_name',
    ];
    
  3. You can now enable it to any Route (just like the L4 filters):

    $router->post('url', ['middleware' => 'shortName', function() {
     ... 
    }]);
    
  1. 创建一个中间件

    php artisan make:middleware class_name
    
  2. 在您的 app/Providers/RouteServiceProvider.php 中创建一个速记键:

    protected $middleware = [
      // ....
      'shortName'  => 'App\Http\Middleware\class_name',
    ];
    
  3. 您现在可以为任何路由启用它(就像 L4 过滤器一样):

    $router->post('url', ['middleware' => 'shortName', function() {
     ... 
    }]);
    

回答by majidarif

It seems like middlewaresare replacing filters for Laravel. As for your question. The right answer is Middlewares. Think of it as layers.

看起来中间件正在取代 Laravel 的过滤器。至于你的问题。正确的答案是中间件。把它想象成层。

For a more detailed answer check thisout.

有关更详细的答案,请查看此内容

old answer

旧答案

A quick search showed requeststo be the new way of validating. But I'm not sure if your use case can apply to this.

快速搜索被证明requests是一种新的验证方式。但我不确定您的用例是否适用于此。

Laravel 5 introduces the notion of “requests”. This is wrapping up logic that you would perform as part of a HTTP request, but are more than just a route filter. A prime candidate: data validation.

Laravel 5 引入了“请求”的概念。这是包装逻辑,您将作为 HTTP 请求的一部分执行,但不仅仅是路由过滤器。主要候选人:数据验证。

One way of doing pre-validation (filter) is by using the method authorize().

进行预验证(过滤器)的一种方法是使用方法authorize()

<?php namespace App\Http\Requests\Auth;

use Illuminate\Foundation\Http\FormRequest;

class RegisterRequest extends FormRequest {

    public function rules()
    {
        return [
            'email' => 'required|email|unique:users',
            'password' => 'required|confirmed|min:8',
        ];
    }

    public function authorize()
    {
        return true;
    }

}

There's a rules() method that returns an array of rules you would before pass to Validator::make(), and also an authorize() method where you would provide any user authorisation. Usually you want all users to be able to register, so you just simply return true.

有一个 rules() 方法,它返回一个你在传递给 Validator::make() 之前会用到的规则数组,还有一个 authorize() 方法,你可以在其中提供任何用户授权。通常您希望所有用户都能够注册,因此您只需简单地返回 true。

Taken from What's new in Laravel 5

取自Laravel 5 的新功能

回答by ugochimbo

For the comment on before/after.

对于之前/之后的评论。

From the linkabove :

从上面的链接

In Middleware..

在中间件..

#Before
public function handle($request, Closure $next)
{
   //Do stuff
   return $request;
}

#After
public function handle($request, Closure $next)
{
   $response = $next($request);

  // Do stuff {on $response}
   return $response;
}

Using ['middleware' => 'shortName']should treat it accordingly.

使用['middleware' => 'shortName']时应相应对待。

回答by Marwan

filters.php has been removed and replaced by Kernel.php beside routes.php

过滤器.php已被删除并由routes.php旁边的Kernel.php取代

protected $routeMiddleware = [
    'auth' => 'App\Http\Middleware\Authenticate',
    'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
    'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
];

But you can't directly add your filter code directly, you should first create a Middleware class (app/Http/Middleware) Then but your desired key in Kernel.php file and reference its own Middleware class, such as:

但是你不能直接添加你的过滤器代码,你应该先创建一个中间件类(app/Http/Middleware)然后在Kernel.php文件中你想要的key并引用它自己的Middleware类,例如:

'product.check' => 'App\Http\Middleware\ProductChecker'

回答by Hamza Ouaghad

I personally think that adding a middleware is a good practice, but if you happen to ever need a quick small filtering for a controller, rubyonrails-style,

我个人认为添加中间件是一个很好的做法,但是如果您碰巧需要对控制器进行快速的小型过滤,rubyonrails 风格,

do as follows:

做如下:

class myController{

   //filters
   public function myFilter()
   {
      //my filter's logic
   }

   public function __construct()
   {
     $this->myFilter();
     //middlewares or any other code
   }


 }

回答by Maykonn

Yes, middleware is the correct place, from Laravel 5.0 docs:

是的,中间件是正确的地方,来自Laravel 5.0 文档

HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application.

HTTP 中间件提供了一种方便的机制来过滤进入应用程序的 HTTP 请求。

回答by Lakin Mohapatra

Now laravel 5 has introduced middleware instead of filters which was present in laravel 4. I will suggest you to follow laravel 5 official docs.

现在 Laravel 5 引入了中间件,而不是 Laravel 4 中存在的过滤器。我建议您关注 Laravel 5官方文档