What is middleware in Laravel and how do you use it?

Middleware in Laravel is a type of filter that sits between the incoming HTTP request and the application’s response. It can be used to perform actions on the request or response, such as authentication, input validation, logging, and more. Middleware is a powerful feature of Laravel that helps to keep the application code clean, organized, and maintainable.

Middleware in Laravel can be defined in two ways:

Closure middleware: Closure middleware is defined using a Closure function. It is useful for simple middleware that does not require a lot of configuration. For example, the following middleware can be used to check if the user is authenticated:


Route::get('/dashboard', function () {
//
})->middleware(function ($request, $next) {
if (Auth::check()) {
return $next($request);
}
return redirect('/login');
});

Here, the middleware function checks if the user is authenticated using the Auth::check() method. If the user is authenticated, the middleware passes the request to the next middleware or the controller using the $next parameter. If the user is not authenticated, the middleware redirects the user to the login page.

Class middleware: Class middleware is defined using a class that implements the Middleware interface. It is useful for more complex middleware that requires configuration and dependencies. For example, the following middleware can be used to log the incoming requests:
php
Copy code
class LogRequestsMiddleware implements Middleware
{
public function handle($request, Closure $next)
{
Log::info(‘Received request: ‘ . $request->getPathInfo());

return $next($request);
}
}
Here, the middleware class logs the incoming request using the Log::info() method and passes the request to the next middleware or the controller using the $next parameter.

To use middleware in Laravel, you can either apply it to a specific route or group of routes using the middleware method, or you can apply it globally to all routes using the $middleware property in the App\Http\Kernel class.

For example, to apply the LogRequestsMiddleware to a specific route, you can do the following:

Route::get(‘/dashboard’, ‘DashboardController@index’)->middleware(LogRequestsMiddleware::class);
Or, to apply the middleware globally, you can add it to the $middleware property in the App\Http\Kernel class:

protected $middleware = [
// …
LogRequestsMiddleware::class,
];

This will apply the LogRequestsMiddleware to all incoming requests in your application.