I have two Middlewares: beforeCache & afterCache, boths registered on Kernel.
I want to call them into routes in this order: 1. beforeCache 2. myController 3. afterCache
If I define a route like this:
Route::get('especies/{id}', [
'middleware' => 'beforeCache',
'uses' => 'MyController@myMethod',
'middleware' => 'afterCache',
]);
beforeCache don't executes because afterCache is redefining the same array key middleware.
How should I do that? Thanks!
For Before middlewares you do your code and return the next request after your code executes. For After middleware you handle the rest of the request and then your code executes and finally return the response.
Laravel framework comes with several middlewares, including midlewares for — authentication and CSRF protection. The default middleware are located in the app/Http/Middleware directory.
There are two types of Middleware in Laravel. The Global Middleware will run on every HTTP request of the application, whereas the Route Middleware will be assigned to a specific route. The middleware can be registered at app/Http/Kernel.
Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated.
I'll assume you're using 5.1 in this, but what you're doing is essentially trying to define an array of attributes on the route. The brackets [] are just a shorthand version of saying array(...).
From the documentation (http://laravel.com/docs/5.1/middleware#defining-middleware) specifically the Before / After Middleware you simply just need to return a certain way.
For Before middlewares you do your code and return the next request after your code executes.
public function handle($request, Closure $next)
{
// Perform action
return $next($request);
}
For After middleware you handle the rest of the request and then your code executes and finally return the response.
public function handle($request, Closure $next)
{
$response = $next($request);
// Perform action
return $response;
}
The route would end up looking like this,
Route::get('especies/{id}',[
'middleware' => [
'beforeCache',
'afterCache'
],
'uses' => 'MyController@myMethod'
]);
class BeforeMiddleware implements Middleware {
public function handle($request, Closure $next)
{
// Do Stuff
return $next($request);
}
}
class AfterMiddleware implements Middleware {
public function handle($request, Closure $next)
{
$response = $next($request);
// Do stuff
return $response;
}
}
1-The before middleware operates and then passes on the request.
2-The after middleware allows the request to be processed, and then operates on it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With