Filters in Laravel 5

2019-03-08 22:20发布

问题:

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

回答1:

The short answer is no, route filters are not going 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.

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

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.

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/.

2015-05-29 Update: Middleware parameters are available starting with 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.



回答2:

  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() {
     ... 
    }]);
    


回答3:

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

For a more detailed answer check this out.

old answer

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

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.

One way of doing pre-validation (filter) is by using the method 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.

Taken from What's new in Laravel 5



回答4:

For the comment on before/after.

From the link above :

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.



回答5:

filters.php has been removed and replaced by Kernel.php beside routes.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:

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


回答6:

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

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



回答7:

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,

do as follows:

class myController{

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

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


 }


回答8:

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.