Laravel 5: Middleware before & after into routes

✔ Recommended Answer

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']);

Source: stackoverflow.com

Answered By: Sieabah

Method #2

In Laravel 5, you can assign middleware to run either before or after a route by specifying it in the route definition. Here's an example:

php
// Middleware to run before the route Route::get('/admin', function () { // ... })->middleware('auth'); // Middleware to run after the route Route::get('/profile', function () { // ... })->middleware('log');

In this example, the first route definition assigns the auth middleware to run before the route is executed. The auth middleware could be used to verify that the user is authenticated before allowing access to the /admin route.

The second route definition assigns the log middleware to run after the route is executed. The log middleware could be used to log information about the request after it has been processed.

You can also assign multiple middleware to a route by passing an array of middleware names:

php
Route::get('/dashboard', function () { // ... })->middleware(['auth', 'log']);

In this example, both the auth and log middleware will run before and after the route, respectively.

Note that middleware can also be assigned globally to all routes, to a group of routes, or to a controller. For more information, see the Laravel documentation on middleware: https://laravel.com/docs/5.0/middleware

Comments

Most Popular

Remove Unicode Zero Width Space PHP

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755