- Register Middleware
- Middleware Parameters
- Terminable Middleware

Middleware acts as a middle man between request and response, provide a mechanism for filtering HTTP requests.
For example, Laravel includes a middleware that verifies whether user of the application is authenticated or not. If the user is authenticated, he will be redirected to the home page otherwise, he will be redirected to the login page.

There are several middleware included in the Laravel framework, including middleware for authentication and CSRF protection. All of these middleware are located in the app/Http/Middleware/ directory.

Define Middleware

You can create your own middleware to filter and parse the requests before getting response.
To create a Middleware you can use the 'artisan make:middleware' command in CLI.
php artisan make:middleware MiddlewareName
- Example, in Command Line Interface navigate to the folder with your Laravel project, and execute this command to create a CheckAge middleware:
php artisan make:middleware CheckAge
This will create a new file named "CheckAge.php" in app/Http/Middleware/ folder, with a CheckAge class and a handle() method:
namespace App\Http\Middleware;

use Closure;

class CheckAge {
  //Handle an incoming request.
  //@param  \Illuminate\Http\Request  $request
  //@param  \Closure $next
  //@return mixed
  public function handle($request, Closure $next){
    if($request->age <=200) echo $request->age; //added for tests
    return $next($request);
  }
}
- I added the line of code: "if($request->age <=200)" to use it for tests.
The middleware handle() method is executed before the controller.

Register Middleware

Before using a middleware, you have to register it in the app/Http/Kernel.php class. This class contains three properties: $middleware, $routeMiddleware, $middlewareGroups.
There are two types of Middleware in Laravel: Global Middleware and Route Middleware.

Global Middleware

The Global Middleware will automatically run on every HTTP request of the application.
To register a Global Middleware, list the class at the end of the $middleware property, like in the code bellow.

- Here is an example for test.
1. Add the CheckAge class in the $middleware' property (in the app/Http/Kernel.php class).
protected $middleware =[
  \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
  \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
  \App\Http\Middleware\TrimStrings::class,
  \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
  \App\Http\Middleware\TrustProxies::class,
  \App\Http\Middleware\CheckAge::class //-for test
];
2. Now, access these URLs in your browser:
This URL will display 99; due to the "if($request->age <=200) echo $request->age;" in CheckAge middleware
    //localhost:8000/?age=99

This URL will not display 299; because the age is higher than 200
    //localhost:8000/?age=299

Route Middleware

The Route Middleware will be assigned to a specific route.
To register a Route Middleware, append it to the list of the $routeMiddleware property, and assign it a key of your choosing, like in the code bellow.
For example:
protected $routeMiddleware = [
  'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
  'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
  'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
  'can' => \Illuminate\Auth\Middleware\Authorize::class,
  'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
  'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
  'age'=> \App\Http\Middleware\CheckAge::class //-for test
];
Once the middleware has been added in the $routeMiddleware property, you may use the middleware method to assign middleware to a route (using its registered key):
Route::get('admin/profile', function(){
  //
})->middleware('auth');
- You may also assign multiple middleware to a route:
Route::get('/', function(){
  //
})->middleware('auth', 'age');
You can also use a middleware class without registering it in Kernel.php, by including it with "use" in the "routes/web.php".
Then, pass the ClassName::class to the middleware() method in Route:
use App\Http\Middleware\CheckAge;

Route::get('admin/profile', function(){
  //
})->middleware(CheckAge::class);

Middleware Groups

Middleware Groups can be used to group several middleware under a single key.
To create middleware group, use the $middlewareGroups property in Kernel.php.
- Laravel comes with "web" and "api" middleware groups that contains common middleware you may want to apply to your web UI and API routes:
protected $middlewareGroups = [
  'web' =>[
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    // \Illuminate\Session\Middleware\AuthenticateSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    \App\Http\Middleware\VerifyCsrfToken::class,
    \Illuminate\Routing\Middleware\SubstituteBindings::class
  ],

  'api' =>[
    'throttle:60,1',
    'bindings'
  ],

  //for exemplification
  'group_name'=>[
    \App\Http\Middleware\Middleware::class,
    \App\Http\Middleware\OtherMiddleware::class,
  ]
];
The 'web' middleware group is automatically applied to routes/web.php file by the RouteServiceProvider.

Middleware groups may be assigned to routes and controller actions using the same syntax as individual middleware:
//assign middleware group_name to this route
Route::get('/', 'MyController@index')->middleware('group_name');

//assign group_name to a group of routes
Route::group(['middleware' => ['group_name']], function () {
  //here you can add several routes
});

Middleware Parameters

Middleware can also receive additional parameters. You can add additional parameters after the $next argument in the middleware method.
- For example, we can set a $role parameter in the handle() method of the middleware class we have created.
public function handle($request, Closure $next, $role){
  echo $role;
  return $next($request);
}
Middleware parameters may be specified when defining the route by separating the middleware name and parameters with a ":".
//pass 'role_value' for the first additional parameter ($role) to middleware registered with the key 'age' in $routeMiddleware (in Kernel.php) Route::name('home')->get('/', 'MyController@index')->middleware('age:role_value');
- Now, if you access: "//localhost:8000/", it will show the string "role_value".

Terminable Middleware

Terminable middleware performs some task after the response has been sent to the browser.
- The handle() method of the middleware class it is executed before sending the request to controller.
To perform some instructions after the response has been sent to the browser, define a terminate() method in your middleware.
The terminate() method should receive both the $request and the $response arguments.
namespace App\Http\Middleware;

use Closure;

class CheckAge {
  //Handle an incoming request.
  //@param  \Illuminate\Http\Request  $request
  //@param  \Closure $next
  //@return mixed
  public function handle($request, Closure $next){
    if($request->age <=200) echo $request->age;
    return $next($request);
  }

  //executed after the response has been sent to browser
  public function terminate($request, $response){
    echo '<br>Executing statements of terminate method of CheckAge.';
  }
}
- Terminable middleware should be registered in the list of the $middleware or $routeMiddleware properties in app/Http/Kernel.php.
The terminate() method will automatically be called after the response is sent to the browser.

- Documentation: Laravel - Middleware

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which HTML5 tag can be used to embed an external application (SWF, PDF) in web page?
<mark> <embed> <canvas>
<embed src="flash_game.swf" width="450" height="350" />
Which CSS pseudo-element adds a special style to the first line of a text?
:first-letter :before :first-line
#id:first-line {
  font-weight: bold;
  color: blue;
}
Click on the window object property which gets or sets the URL of current page.
window.location window.self window.status
var url = window.location;
alert(url);
Indicate the PHP function used to get the contents of a file or page and store it into a string.
fopen() file_put_contents() file_get_contents()
$homepage = file_get_contents("http://coursesweb.net/");
echo $homepage;
Laravel Middleware

Last accessed pages

  1. Drag Racer V3 (26088)
  2. SHA512 Encrypt hash in JavaScript (7818)
  3. Flash Games - Free online Games (21262)
  4. innerHTML and outerHTML to Get and Replace HTML content (13948)
  5. Stunt Driver 3d (790)

Popular pages this month

  1. Qwop (4606)
  2. Drag Racer V3 (2233)
  3. Flash Games - Free online Games (1106)
  4. Bubbles3 (992)
  5. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (981)