Laravel

Middleware

Middleware creation, global middleware, route middleware, middleware groups, middleware parameters, terminable middleware

18 interview questions·
Mid-Level
1

What is a middleware in Laravel?

Answer

A middleware is an HTTP filtering mechanism that inspects and modifies incoming requests and/or outgoing responses. It acts as an intermediary layer between the client's request and the application's response, allowing code execution before or after request processing by the controller. Middlewares are used for authentication, CSRF validation, logging, header modification, etc.

2

How to create a new middleware using Artisan?

Answer

The php artisan make:middleware command generates a new middleware in the app/Http/Middleware directory. This command creates a class with a handle method that accepts the request and a next closure. The middleware can then be registered globally, in a group, or assigned to specific routes via the bootstrap/app.php file or directly in routes.

3

Which method of a middleware is automatically called when processing an HTTP request?

Answer

The handle method is automatically called for each middleware registered on a route. It receives two parameters: the Request object and a next closure that represents the next middleware in the stack. To continue processing, you must call next with the request. This architecture enables creating a chain of responsibility where each middleware can inspect, modify or interrupt the processing flow.

4

How to register a middleware globally for all HTTP requests in the application?

5

How to assign a middleware to a specific route?

+15 interview questions

Master Laravel for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free