Middleware Mechanism in Laravel

Last updated on Oct 05 2022
Harish Chopra

Table of Contents

Middleware Mechanism in Laravel

Middleware acts as a bridge between a request and a response. It is a type of filtering mechanism. This blog explains you the middleware mechanism in Laravel.

Laravel includes a middleware that verifies whether the user of the application is authenticated or not. If the user is authenticated, it redirects to the home page otherwise, if not, it redirects to the login page.

Middleware can be created by executing the following command −

php artisan make:middleware <middleware-name>

Replace the <middleware-name> with the name of your middleware. The middleware that you create can be seen at app/Http/Middleware directory.

Example

Observe the following example to understand the middleware mechanism −

Step 1 − Let us now create AgeMiddleware. To create that, we need to execute the following command −

php artisan make:middleware AgeMiddleware

Step 2 − After successful execution of the command, you will receive the following output −

la 29

Step 3 − AgeMiddleware will be created at app/Http/Middleware. The newly created file will have the following code already created for you.

<?php namespace App\Http\Middleware;use Closure; class AgeMiddleware {   public function handle($request, Closure $next) {      return $next($request);   }}

Registering Middleware

We need to register each and every middleware before using it. There are two types of Middleware in Laravel.

  • Global Middleware
  • Route Middleware

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.php. This file contains two properties $middleware and $routeMiddleware$middleware property is used to register Global Middleware and $routeMiddleware property is used to register route specific middleware.

To register the global middleware, list the class at the end of $middleware property.

protected $middleware = [   \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,   \App\Http\Middleware\EncryptCookies::class,   \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,   \Illuminate\Session\Middleware\StartSession::class,   \Illuminate\View\Middleware\ShareErrorsFromSession::class,   \App\Http\Middleware\VerifyCsrfToken::class,];

To register the route specific middleware, add the key and value to $routeMiddleware property.

protected $routeMiddleware = [   'auth' => \App\Http\Middleware\Authenticate::class,   'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,   'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,];

Example

We have created AgeMiddleware in the previous example. We can now register it in route specific middleware property. The code for that registration is shown below.

The following is the code for app/Http/Kernel.php −

<?php namespace App\Http;use Illuminate\Foundation\Http\Kernel as HttpKernel; class Kernel extends HttpKernel {   protected $middleware = [      \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,      \App\Http\Middleware\EncryptCookies::class,      \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,      \Illuminate\Session\Middleware\StartSession::class,      \Illuminate\View\Middleware\ShareErrorsFromSession::class,      \App\Http\Middleware\VerifyCsrfToken::class,   ];     protected $routeMiddleware = [      'auth' => \App\Http\Middleware\Authenticate::class,      'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,      'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,      'Age' => \App\Http\Middleware\AgeMiddleware::class,   ];}

Middleware Parameters

We can also pass parameters with the Middleware. For example, if your application has different roles like user, admin, super admin etc. and you want to authenticate the action based on role, this can be achieved by passing parameters with middleware. The middleware that we create contains the following function and we can pass our custom argument after the $next argument.

public function handle($request, Closure $next) {   return $next($request);}

Example

Step 1 − Create RoleMiddleware by executing the following command −

php artisan make:middleware RoleMiddleware

Step 2 − After successful execution, you will receive the following output −

la 30

Step 3 − Add the following code in the handle method of the newly created RoleMiddlewareat app/Http/Middleware/RoleMiddleware.php.

<?php namespace App\Http\Middleware;use Closure; class RoleMiddleware {   public function handle($request, Closure $next, $role) {      echo "Role: ".$role;      return $next($request);   }}

Step 4 − Register the RoleMiddleware in app\Http\Kernel.php file. Add the line highlighted in gray color in that file to register RoleMiddleware.

la 37

 

Step 5 − Execute the following command to create TestController −

php artisan make:controller TestController --plain

Step 6 − After successful execution of the above step, you will receive the following output −

la 31

Step 7 − Copy the following lines of code to app/Http/TestController.php file.

app/Http/TestController.php

<?php namespace App\Http\Controllers; use Illuminate\Http\Request;use App\Http\Requests;use App\Http\Controllers\Controller; class TestController extends Controller {   public function index() {      echo "<br>Test Controller.";   }}

Step 8 − Add the following line of code in app/Http/routes.php file.

app/Http/routes.php

Route::get('role',[   'middleware' => 'Role:editor',   'uses' => 'TestController@index',]);

Step 9 − Visit the following URL to test the Middleware with parameters

http://localhost:8000/role

Step 10 − The output will appear as shown in the following image.

la 32

Terminable Middleware

Terminable middleware performs some task after the response has been sent to the browser. This can be accomplished by creating a middleware with terminate method in the middleware. Terminable middleware should be registered with global middleware. The terminate method will receive two arguments $request and $response. Terminate method can be created as shown in the following code.

Example

Step 1 − Create TerminateMiddleware by executing the below command.

php artisan make:middleware TerminateMiddleware

Step 2 − The above step will produce the following output −

la 33

Step 3 − Copy the following code in the newly created TerminateMiddleware at app/Http/Middleware/TerminateMiddleware.php.

<?php namespace App\Http\Middleware;use Closure; class TerminateMiddleware {   public function handle($request, Closure $next) {      echo "Executing statements of handle method of TerminateMiddleware.";      return $next($request);   }      public function terminate($request, $response) {      echo "<br>Executing statements of terminate method of TerminateMiddleware.";   }}

Step 4 − Register the TerminateMiddleware in app\Http\Kernel.php file. Add the line highlighted in gray color in that file to register TerminateMiddleware.

la 34

Step 5 − Execute the following command to create ABCController.

php artisan make:controller ABCController --plain

Step 6 − After the successful execution of the URL, you will receive the following output −

la 35

Step 7 − Copy the following code to app/Http/ABCController.php file.

app/Http/ABCController.php

<?php namespace App\Http\Controllers; use Illuminate\Http\Request;use App\Http\Requests;use App\Http\Controllers\Controller; class ABCController extends Controller {   public function index() {      echo "<br>ABC Controller.";   }}

Step 8 − Add the following line of code in app/Http/routes.php file.

app/Http/routes.php

Route::get('terminate',[   'middleware' => 'terminate',   'uses' => 'ABCController@index',]);

Step 9 − Visit the following URL to test the Terminable Middleware.

http://localhost:8000/terminate

Step 10 − The output will appear as shown in the following image.

la 36

So, this brings us to the end of blog. This Tecklearn ‘Middleware Mechanism in Laravel’ blog helps you with commonly asked questions if you are looking out for a job in Laravel Programming. If you wish to learn Laravel and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

https://www.tecklearn.com/course/java-and-jee-training/

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

  • Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
  • Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
  • Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

  • Java Fundamentals
  • Introduction to Java Basics
  • Features of Java
  • Various components of Java language
  • Benefits of Java over other programming languages
  • Key Benefits of Java

Installation and IDE’s for Java Programming Language

  • Installation of Java
  • Setting up of Eclipse IDE
  • Components of Java Program
  • Editors and IDEs used for Java Programming
  • Writing a Simple Java Program

Data Handling and Functions

  • Data types, Operations, Compilation process, Class files, Loops, Conditions
  • Using Loop Constructs
  • Arrays- Single Dimensional and Multi-Dimensional
  • Functions
  • Functions with Arguments

OOPS in Java: Concept of Object Orientation

  • Object Oriented Programming in Java
  • Implement classes and objects in Java
  • Create Class Constructors
  • Overload Constructors
  • Inheritance
  • Inherit Classes and create sub-classes
  • Implement abstract classes and methods
  • Use static keyword
  • Implement Interfaces and use it

Polymorphism, Packages and String Handling

  • Concept of Static and Run time Polymorphism
  • Function Overloading
  • String Handling –String Class
  • Java Packages

Exception Handling and Multi-Threading

  • Exception handling
  • Various Types of Exception Handling
  • Introduction to multi-threading in Java
  • Extending the thread class
  • Synchronizing the thread

File Handling in Java

  • Input Output Streams
  • io Package
  • File Handling in Java

Java Collections

  • Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
  • Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
  • Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

  • Introduction to SQL: Connect, Insert, Update, Delete, Select
  • Introduction to JDBC and Architecture of JDBC
  • Insert/Update/Delete/Select Operations using JDBC
  • Batch Processing Transaction
  • Management: Commit and Rollback

Java Enterprise Edition – Servlets

  • Introduction to J2EE
  • Client Server architecture
  • URL, Port Number, Request, Response
  • Need for servlets
  • Servlet fundamentals
  • Setting up a web project in Eclipse
  • Configuring and running the web app with servlets
  • GET and POST request in web application with demo
  • Servlet lifecycle
  • Servlets Continued
  • Session tracking and filter
  • Forward and include Servlet request dispatchers

Java Server Pages (JSP)

  • Fundamentals of Java Server Page
  • Writing a code using JSP
  • The architecture of JSP
  • JSP Continued
  • JSP elements: Scriptlets, expressions, declaration
  • JSP standard actions
  • JSP directives
  • Introduction to JavaBeans
  • ServletConfig and ServletContext
  • Servlet Chaining
  • Cookies Management
  • Session Management

Hibernate

  • Introduction to Hibernate
  • Introduction to ORM
  • ORM features
  • Hibernate as an ORM framework
  • Hibernate features
  • Setting up a project with Hibernate framework
  • Basic APIs needed to do CRUD operations with Hibernate
  • Hibernate Architecture

POJO (Plain Old Java Object)

  • POJO (Plain Old Java Object)
  • Persistent Objects
  • Lifecycle of Persistent Object

Spring

  • Introduction to Spring
  • Spring Fundamentals
  • Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

0 responses on "Middleware Mechanism in Laravel"

Leave a Message

Your email address will not be published. Required fields are marked *