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
What attribute makes a radio button or checkbox input selected?
checked="checked" selected="selected" disabled="disabled"
<input type="checkbox" name="a_name" value="value" checked="checked" />
What CSS value scales the background image to the largest size contained within the element?
repeat-x contain linear-gradient
#id {
  background:url("path_to_image.png");
  background-size:contain;
  background-repeat:no-repeat;
}
What operator is used to determine the rest of the division of two numbers?
% * /
var rest8_7 = 8 % 7;
alert(rest8_7);
Indicate the PHP function that rounds a number up to the next highest integer.
floor() ceil() abs()
$nr = ceil(3.5);
echo $nr;        // 4
Laravel Middleware

Last accessed pages

  1. The School for Gods (6073)
  2. sPBM - Simple PHP Backup Manager (3390)
  3. querySelector and querySelectorAll (30115)
  4. CSS3 2D transforms (820)
  5. How to get JSON data from JavaScript to PHP (617)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (55)
  2. The Mastery of Love (9)
  3. CSS cursor property - Custom Cursors (9)
  4. CSS3 2D transforms (7)
  5. Read Excel file data in PHP - PhpExcelReader (7)