# Middlewares

Middlewares are a tool to secure your routes and you can register them inside app\Http\Kernel.php.

Middlewares can also be used to alter a request before hitting the route.

# Global middlewares

By default, Tea comes with a global middleware called CheckForMaintenance. CheckForMaintenance will check if the application is down, if the application is down, then the maintenance page will display.

To put the application under maintenance run: php tea down

To bring the application up run: php tea up

# Route middlewares

You can create your own custom middlewares by running:

php tea make:middleware name=IsAdmin

<?php

namespace App\Http\Middlewares;

class IsAdmin
{
    public function handle()
    {
        if (false) {
            return json([
                'message' => 'Unauthorized'
            ], 403);
        }

        return true;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# Registering route middlewares

After creating a route middleware, we register the middleware inside app\Http\Kernel.php, $routeMiddlewares array:

<?php

namespace App\Http;

use App\Http\Middlewares\IsAdmin;
use Devlob\Http\HttpKernel;
use Devlob\Http\Middlewares\Api;
use Devlob\Http\Middlewares\CheckForMaintenance;
use Devlob\Http\Middlewares\PresentSecretKey;

class Kernel extends HttpKernel
{
    protected $globalMiddlewares = [
        CheckForMaintenance::class,
        PresentSecretKey::class
    ];

    protected $routeMiddlewares = [
        'api' => Api::class,
        'isAdmin' =>  IsAdmin::class
    ];
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

and we can use it as described below:

$router->get('/users/{id}', 'UserController@show')->middlewares(['isAdmin']);
1

Middlewares will execute in the order you specify them.

In the example below, run1st will execute first, run2nd will execute second and run3rd will execute last.

$router->get('/users/{id}', 'UserController@show')->middlewares(['run1st', 'run2nd', 'run3rd']);
1