Middlewares
Route middleware provides a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, middleware can verify if the user of your application is authenticated. If the user is not authenticated, the middleware will throw an exception. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.
Introduction
Middleware modules are the layers that surround your application core. They can be used for logging, authentication, CORS handling, and more. All middlewares in the Droip Ecommerce system must implement the Ecommerce\Contracts\Middleware interface.
Attaching Middleware
You can attach middleware to individual routes or groups of routes to filter incoming requests.
Attach to Single Route
Attach a specific middleware or list of middlewares to a route.
Description:
The middleware() method allows you to assign one or more middleware classes to a specific route. These middlewares are executed in the order they are assigned before the route handler is invoked. This is useful for route-specific logic like permission checks or data validation.
Method Signature:
public function middleware(string|array $middleware): Route
Parameters:
$middleware- The fully qualified class name or array of class names of the middleware.
Examples:
use Ecommerce\Core\Route;
use Ecommerce\Middlewares\AuthMiddleware;
use Ecommerce\Middlewares\CheckStockMiddleware;
// Attach a single middleware
Route::get('/products/{id}', [ProductController::class, 'show'])
->middleware(AuthMiddleware::class);
// Attach multiple middlewares
Route::post('/orders', [OrderController::class, 'store'])
->middleware([
AuthMiddleware::class,
CheckStockMiddleware::class
]);
Group Routes with Middleware
Apply middleware to a group of routes using shared options.
Description:
The group() method allows you to define a set of routes that share common attributes, such as middleware. By passing a middleware option in the group array, you can ensure that all routes defined within the closure are protected by the specified middleware. This is ideal for protecting entire sections of your API, such as administrative endpoints.
Method Signature:
public static function group(array $options, Closure $closure): void
Parameters:
$options- Array of shared options. Use['middleware' => 'ClassName']or['middleware' => ['ClassA', 'ClassB']].$closure- A closure that defines the routes within the group.
Examples:
use Ecommerce\Core\Route;
use Ecommerce\Middlewares\AuthMiddleware;
use Ecommerce\Middlewares\AdminMiddleware;
// Group routes with authentication middleware
Route::group(['middleware' => AuthMiddleware::class], function () {
Route::get('/profile', [UserController::class, 'profile']);
Route::put('/profile/update', [UserController::class, 'update']);
});
// Group with multiple middlewares
Route::group(['middleware' => [AuthMiddleware::class, AdminMiddleware::class]], function () {
Route::post('/products', [ProductController::class, 'store']);
Route::delete('/products/{id}', [ProductController::class, 'destroy']);
// Nested group
Route::group(['prefix' => 'settings'], function () {
Route::get('/', [SettingsController::class, 'index']);
});
});
Defining Middleware
You can define your own middleware to handle custom request filtering logic.
Define Custom Middleware
Implement the Middleware interface to create custom request filters.
Description:
To create a custom middleware, you must implement the Ecommerce\Contracts\Middleware interface. The handle method is the entry point for the middleware. It receives the incoming Request object and a next closure. You can perform logic before or after passing the request to the next layer. If you wish to stop the request, you can throw an exception or return a response immediately.
Method Signature:
public function handle(Request $request, callable $next);
Parameters:
$request- TheEcommerce\Http\Requestinstance representing the current request.$next- The next callable in the middleware pipeline.
Examples:
namespace Ecommerce\Middlewares;
use Ecommerce\Contracts\Middleware;
use Ecommerce\Contracts\Request;
use Ecommerce\Exceptions\AuthorizationException;
use Ecommerce\Models\Product;
class CheckStockMiddleware implements Middleware
{
/**
* Check if the product is in stock.
*/
public function handle(Request $request, callable $next)
{
$productId = $request->get('product_id');
if ($productId) {
$product = Product::find($productId);
if (!$product || $product->stock <= 0) {
throw new AuthorizationException('Product out of stock');
}
}
return $next($request);
}
}
// Registering and using the middleware
Route::post('/cart/add', [CartController::class, 'add'])
->middleware(CheckStockMiddleware::class);