Filters in Laravel 5

后端 未结 8 973
南笙
南笙 2021-01-31 08:12

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

相关标签:
8条回答
  • 2021-01-31 08:45

    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.

    0 讨论(0)
  • 2021-01-31 08:46

    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'
    
    0 讨论(0)
提交回复
热议问题