HTTP Middleware:-
- Laravel includes a middleware that verifies the user of an application whether the user is authenticated or not.
- If the user is not authenticated, then the middleware will redirect the user to the login screen.
- If it doesn't happen, i.e, if the user is authenticated, the middleware will allow the request to proceed further into the application.
- There are several middleware included in the Laravel framework, which includes middleware for maintenance, authentication, CSRF protection, and more.
- All of these middleware are located in the app/Http/Middleware directory.
- To create a new middleware, use the make:middleware Artisan command:-
php artisan make:middleware Middleware1
- The above command will place a new Middleware1 class within our app/Http/Middleware directory.
- Discussing it with a suitable example:-
<?php
namespace App\Http\Middleware;
use Closure;
class Middleware1
{
public function request($request, Closure $next)
{
if ($request‐>input('roll') <= 50) {
return redirect('home');
}
return $next($request);
}
}
- In the above example, we will only allow access to the route if the supplied roll is greater than 50.
- Otherwise, we will redirect the users back to the "home" URL.
- If we want a middleware to be run during every HTTP request to our application, we need to list the middleware class in the $middleware property of our app/Http/Kernel.php class.
- If we would like to assign middleware to specific routes, we should first assign the middleware a shorthand key in our app/Http/Kernel.php file.
- By default, the $routeMiddleware property contains entries for the middleware included with Laravel.
- Once the middleware has been defined in the HTTP kernel, we may use the middleware key in the route options array:-
//
}]);
No comments:
Post a Comment