How do we make filters in Laravel 5? Is the idea of filters going away?
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
}
}
Create a middleware with
php artisan make:middleware class_name
Create a short-hand key in your app/Providers/RouteServiceProvider.php :
protected $middleware = [
// ....
'shortName' => 'App\Http\Middleware\class_name',
];
You can now enable it to any Route (just like the L4 filters):
$router->post('url', ['middleware' => 'shortName', function() {
...
}]);
Yes, middleware is the correct place, from Laravel 5.0 docs:
HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application.
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.
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.
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.
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