Laravel Course

- 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 meta tag provides a short description of the page?
<meta content="..."> <meta description="..."> <meta http-equiv="...">
<meta name="description" content="70-160 characters that describes the content of the page" />
Which CSS property is used to stop the wrapping effect of the "float"?
clear text-align position
#some_id {
  clear: both;
}
Click on the method which gets an array with all the elements in the document that have a specified tag name.
getElementsByName() getElementById() getElementsByTagName()
var divs = document.getElementsByTagName("div");
var nr_divs = divs.length;
alert(nr_divs);
Indicate the PHP function which returns the number of elements in array.
is_[) count() strlen()
$arr =[7, 8, "abc", 10);
$nri = count($arr);
echo $nri;        // 4
Laravel Middleware

Last accessed pages

  1. JavaScript Course - Free lessons (31411)
  2. Properties and Methods of the Form elements (594)
  3. PHP Strings (3263)
  4. Selection Tools (8145)
  5. Get Lower, Higher, and Closest Number (5342)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (201)
  2. Read Excel file data in PHP - PhpExcelReader (66)
  3. The Mastery of Love (56)
  4. PHP Unzipper - Extract Zip, Rar Archives (51)
  5. Working with MySQL Database (34)
Chat
Chat or leave a message for the other users
Full screenInchide