Middleware
Middleware provide a convenient mechanism for filtering HTTP requests entering your application.
Defining Middleware
To create a new middleware, use the m:ware Atom command:
php atom g:ware CheckDate
or
php atom generate:middleware CheckDate
This command will place a new CheckDate class within your app/middlewares directory. In this middleware, we will only allow access to the route if the supplied date is greater than today. Otherwise, we will redirect the users back to the home URI:
<?php
namespace App\Middlewares;
class CheckDate
{
/**
* Handle an incoming request.
*
* @return mixed
*/
public function handle()
{
if (request()->input('date') <= moment()) {
return redirect('home');
}
}
}
As you can see, if the given date is less than or equal to the current date, the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application.
It's best to envision middleware as a series of "layers" HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.
Assign Middleware To Route
use App\Middlewares\CheckAge;
router()->get('admin/profile', function () {
//
})->middleware(CheckDate::class);
Dernière mise à jour
Cet article vous a-t-il été utile ?