Middlewares

Introduction

Middleware provides a convenient mechanism for inspecting and filtering HTTP requests coming into your application.

By default, all of the middlewares for your application are stored in the app/middlewares/ directory.

Using

Middlewares must be specified in the route to use it.

// routes/api.php
use Ghosty\Framework\Support\Facades\Route;

Route::get('/home')
    ->controller(\App\Controllers\HomeController::class)
    ->action('show')
    ->middleware(\App\Middlewares\HomeMiddleware::class);

Here is an example of middleware that displays 'Hello World from Middleware!'

// app/middlewares/HomeMiddleware.php
namespace App\Middlewares;

class HomeMiddleware
{
    public function handle()
    {
        echo 'Hello World! from middleware';
    }
}

Here is an example of HomeController that displays 'Hello World from Controller!'

// app/Controllers/HomeController.php
namespace App\Controllers;

class HomeController
{
    public function index()
    {
        echo 'Hello World from Controller!';
    }
}

If we go to the path /home, then as a result we will receive a message on the screen:
Hello world from Middleware!
Hello world from Controller!