Updated on 01 Jun 2019 | 3 Min Read
By
Importance of middleware in Laravel
 

What is Laravel?

Laravel is an open-source PHP web framework that is free of cost to use. It was designed and developed to create various web applications based on Symphony.

What is Middleware?

In the Laravel interview questions, it is often asked that, what the correlation between the two is? The answer to this question is - The Middleware, as you know, is software, which is a connecting platform between the operating system and the applications that are running on that interface. The functioning of the Middleware is a platform that functions on the same working criteria as that of the “if and else loop.”

  • Global Middleware – Runs on each HTTP related issue. If you want to run Middleware on all the requests, then choose this one.
  • Route Middleware – Runs on a particular HTTP pertaining issue. Keep in mind that if you are going to run Middleware, only on some specific access requests, then select and assign this middleware from the list, and verify conditions.
An Insight about how middleware works in Laravel

If (Condition 1) {
    // Satisfied: HTTP Redirect Yes
} else {
    // Not satisfied: HTTP Redirect No
}

Importance of Middleware in Laravel Filtering HTTP requests

1. A link between the user request and the access

Laravel requires some platform to act as a connecting platform between its programming software and applications as well as the users who want to access those.

2. Verifying user authentication

Various applications that run on the codes processed by Laravel cannot allow everyone to access and use the platform it provides. For this very purpose, Laravel requires Middleware to decide and process whether a particular Laravel platform access request is genuine or not.

3. Processing HTTP access

Middleware renders a platform to provide a convenient mechanism for handling HTTP requests present in your application.

Example

  • To verify the authentication of any user application, Laravel includes Middleware.
  • If the Middleware finds the user login as authenticated, then it will further carry forward with the request to continue to use the application.
  • If the Middleware finds the user login as unauthenticated, then it will decline the user’s request and redirect them to the home screen.

Just look at a typical code to be run by middleware to decide whether to allow the user access to the platform or not.

namespace App\Http\Middleware;
use Closure;
class Before Middleware
{
    public function handle($request, Closure $next)
      {
         // Perform action
         return $next($request);
      }
 }

We have the collection of best interview questions for almost every subject. To know more Best interview questions or interview questions related to any other topic, keep on visiting our website, and be updated.