Article from: learnku.com/laravel/t/2…
What is Laravel middleware?
In a nutshell, the role of middleware in Laravel is to filter HTTP requests and perform different logical operations based on different requests.
We can use middleware to achieve the following functions:
- Specify some routes
- Sets the HTTP response header
- Record the request
- Filter request parameters
- Determines whether to enable site maintenance mode
- Do the necessary operations before and after the response
Custom middleware
The command line makes it easy to create a new middleware by executing the following simple commands
PHP artisan make: Middleware <MiddlewareName> //MiddlewareName is the name of the middleware you want to createCopy the code
Laravel automatically creates a handle only Middleware in the app/Http/Middleware directory by executing the above command.
<? php namespace App\Http\Middleware; use Closure; class RedirectIfSuperAdmin { /** * Handle an incoming request. * * @param \Illuminate\Http\Request$request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request); }}Copy the code
The Handle method is executed when the middleware is called. Note here that the handle method takes two parameters, $request and $next, by default. $REQUEST is used to accept the application’s request group request, and $next passes the request to the application. These two parameters are essential to Handle! Middleware also includes pre-middleware and post-middleware.
“Front-end middleware” as the name implies handles some logic before forwarding the request to the application. On the other hand, after the middleware, runs after the application has processed the request and generated the response.
Front-end middleware:
<? php namespace App\Http\Middleware; use Closure; class RedirectIfSuperAdmin { /** * Handle an incoming request. * * @param \Illuminate\Http\Request$request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {// Your logic is right herereturn $next($request); }}Copy the code
Back-end middleware:
<? php namespace App\Http\Middleware; use Closure; class RedirectIfSuperAdmin { /** * Handle an incoming request. * * @param \Illuminate\Http\Request$request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request); // Your logic is here for example redirect to '/'return $response; }}Copy the code
Categories of middleware
- Global middleware
- Routing middleware
The global middleware runs for each request that hits the application. Laravel comes with most of these middleware ValidatePostSize, for example, TrimStrings, CheckForMaintenanceMode and so on.
Routing middleware only runs such as redirectIfAuthenticated on the routes to which they are connected.
Registered middleware
Any middleware created must be registered, as this is the only way Laravel knows it exists. To register the middleware, simply open a file called kernel.php, which is located in the Http folder, as follows:
This file contains list of all registered middlewares that come with Laravel by default. it contains three major arrays Which this file contains a list of all the registered middleware provided by Laravel by default. It contains three main middleware groups, $middlewareGroups and $routeMiddleware
<? php namespace App\Http; use Illuminate\Foundation\Http\Kernel as HttpKernel; Class Kernel extends HttpKernel {/** * The global HTTP middleware of an application. * * This middleware runs during each request of the application. * * @var array */ 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, ]; /** * application routing middleware group. ** @var array */ 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',]]; /** * Middleware for routing applications. ** These middleware can be assigned to groups or used separately. * * @var array */ 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,
//the just created middlware
'superadmin' => \App\Http\Middleware\RedirectIfSuperAdmin::class,
];
}
Copy the code
The $Middleware array contains the global middleware that runs every HTTP request for your application, so if you want to run a middleware for every request, you should register it here. $middlewareGroups makes it possible to register middleware in a group, making it easier to attach a large amount of middleware to a route by using a group name. The $routeMiddleware array contains each registered routing middleware.
Distributed middleware
There are two main ways to apply registered middleware to routing.
- Through the construction method of the controller
- Through the routing
Middleware is allocated through constructors
There is a great deal of flexibility in constructor method allocation, which provides two important methods except($parameters) and only($parameters), which allow or prevent middleware from applying helper methods to the controller. Instead of using these two methods, the middleware will use each method with the controller.
<? php use Illuminate\Http\Request; class ForumController extends Controller { publicfunction __construct() {/ * *in this case the middleware named auth is applied
to every single function within this controller
*/
$this->middleware('auth');
}
public function viewForum() {return view('index');
}
public function edit($id){
}
public function delete($id) {}}Copy the code
With except and only methods we can choose to apply middleware to the specified method.
<? php use Illuminate\Http\Request; class ForumController extends Controller { publicfunction __construct(){
/**the authentication middleware here applies to all functions but
viewForums() and viewForumDetails() and the opposite of this happens
when you use only()
*/
$this->middleware('auth')->except(['viewForums'.'viewForumDetails']);
}
public function viewForums() {return view('index');
}
public function edit($id){
}
public function delete($id){
}
public function viewForumDetails() {}}Copy the code
Middleware is allocated through routing
If the registered middleware can be directly attached to the route, as follows:
<? PHP // Route::get('admin/profile'.function () {
//action
})->middleware('auth'); /** Method 2 or use a fully qualified class name like this: */ use App\Http\Middleware\CheckAge; Route::get('admin/profile'.function() { // action })->middleware(CheckAge::class); // Route::group(['middleware'= > ['web']], function () {
//action
});
Copy the code
N:B Middleware groups can be assigned to routes like individual middleware
Middleware parameters
Other parameters can be passed to the middleware. A typical example is to assign each user ID to a role, and the middleware checks the role of the user to determine whether it has access to the requested URI. Parameters can be passed to the middleware as follows:
<? PHP // method 1 (Through route) route ::get'admin/profile'.function () {
//action
})->middleware('auth:<role>'); //<role> this should be replaced by any parameters the user wishes to pass. // Method 2 (Through a controller) use Illuminate\Http\Request; class ForumController extends Controller { publicfunction __construct() {$this->middleware('auth:<role>'); }}Copy the code
Multiple parameters can be passed to the middleware by separating each parameter with a comma.
<? php Route::get('admin/profile'.function () {
//action
})->middleware('auth:<role>,<age>,<country>'); //<role>, <age>, <country> this should be replaced by whatever argument the user wishes to pass.Copy the code
These parameters are passed to the handle function of the middleware after the $next variable
<? php class RedirectIfSuperAdmin { /** * Handle an incoming request. * * @param \Illuminate\Http\Request$request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next.$role.$age.$country) {// Use middleware logic to parse parametersreturn $next($request); }}Copy the code
conclusion
To create the middleware, perform the following procedure
- Create the middleware using the artisan command
PHP Artisan make: Middleware name
. - Register middleware in kernel. PHP in app→Http folder
- Write logic in the middleware you create
- Assign middleware to routes or controllers
Conclusion
Laravel middleware makes it easier to secure our routes, filter input, and do many other things without having to write so much logic. Check out the official Laravel documentation here to learn more about middleware features and, most importantly, exercises.
Article from: learnku.com/laravel/t/2… More articles: learnku.com/laravel/c/t…