Laravel Middleware
Middleware acts as a layer between the user and the request. It means that when the user requests the server then the request will pass through the middleware, and then the middleware verifies whether the request is authenticated or not. If the user's request is authenticated then the request is sent to the backend. If the user request is not authenticated, then the middleware will redirect the user to the login screen.
An additional middleware can be used to perform a variety of tasks except for authentication. For example, CORS middleware is responsible for adding headers to all the responses.
Laravel framework includes several middleware such as authentication and CSRF protection, and all these are located in the app/Http/Middleware directory.
We can say that middleware is an http request filter where you can check the conditions.
In middleware, we are going to discuss the following topics:
- Make a middleware
- Apply middleware
- Check condition in middleware
- Route middleware
Creating a middleware
Type the command php artisan make:middleware 'name of the middleware'.
In the above screen, we type the command "php artisan make:middleware CheckAge" where CheckAge is the name of the middleware. The above window shows that the middleware has been created successfully with the name "CheckAge".
To see whether the CheckAge middleware is created or not, go to your project. Our project name is laravelproject, so the path for the middleware would be: C:\xampp\htdocs\laravelproject\app\Http\Middleware.
Apply a Middleware
Middleware can be either applied to all the URLs or some particular URLs.
Let's apply the middleware to all the URLs.
Step 1: Open the kernel.php file. If we want to apply the middleware to all the URLs, then add the path of the middleware in the array of middleware.
- <?php
- namespace App\Http;
- use Illuminate\Foundation\Http\Kernel as HttpKernel;
- class Kernel extends HttpKernel
- {
- /**
- * The application's global HTTP middleware stack.
- *
- * These middleware are run during every request to your application.
- *
- * @var array
- */
- protected $middleware = [ \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
- \Illuminate\Foundation\Http \Middleware\ValidatePostSize::class,
- \App\Http\Middleware\TrimStrings::class,
- \App\Http\Middleware\CheckAge
- ::class,
- \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
- ];
- /**
- * The application's route middleware groups.
- *
- * @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',
- ],
- ];
- /**
- * The application's route middleware.
- *
- * These middleware may be assigned to groups or used individually.
- *
- *
- @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,
- ];
- }
Step 2: Type the command php artisan serve in Git Bash Window.
Step 3: Open the CheckAge.php file, which you have created as a middleware.
- <?php
- namespace App\Http\Middleware;
- use Closure;
- class CheckAge
- {
- /**
- * Handle an incoming request.
- *
- * @param \Illuminate\Http
- \Request $request
- * @param \Closure $next
- * @return mixed
- */
- public function handle($request, Closure $next)
- {
- //return "middleware";
- echo "hello world";
- return $next($request);
- }
- }
Step 4: Now, enter the URL 'http://localhost/laravelproject/public/
Let's apply the middleware to some specific routes.
Step 1: Open the kernel.php file. If we want to apply the middleware to some specific routes
- <?php
- namespace App\Http;
- use Illuminate\Foundation\Http\Kernel as HttpKernel;
- class Kernel extends HttpKernel
- {
- /**
- * The application's global HTTP middleware stack.
- *
- * These middleware are run during every request to your 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,
- ];
- /**
- * The application's route middleware groups.
- *
- * @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',
- ],
- ];
- /**
- * The application's route middleware.
- *
- * These middleware may be assigned to groups or used individually.
- *
- *
- @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,
- 'age' => \App\Http\Middleware\CheckAge::class ];
- }
In the above code, we have added the code, i.e., ''age' => \App\Http\Middleware\CheckAge::class', where age is the name of the middleware. Now, we can use the 'age' middleware for some specific routes.
Step 2: Open the CheckAge.php file, which you have created as a middleware.
Step 3: Add the middleware code in the web.php file.
- Route::Get('/',function()
- {
- return view('welcome');
- })-> middleware('age');
- Route::Get('user/profile',function()
- {
- return "user profile";
- });
In the above code, we have added middleware in '/' root URL, and we have not added the middleware in the 'user/profile' URL.
Output:
When we access the root URL, then the output would be:
The above output shows that the middleware code has also been accessed as it is displaying a "hello world".
When we access the URL, i.e., /user/profile, then the output would be:
The above output that the middleware code has not been accessed.
When the parameter is passed in a URL.
web.php
- Route::Get('/{age}',function($age)
- {
- return view('welcome');
- })-> middleware('age');
CheckAge.php
- <?php
- namespace App\Http\Middleware;
- use Closure;
- class CheckAge
- {
- /**
- * Handle an incoming request.
- *
- * @param
- \Illuminate\Http\Request $request
- * @param \Closure $next
- * @return mixed
- */
- public function handle($request, Closure $next)
- {
- //return "middleware";
- echo "this is checkage middleware";
- return $next($request);
- }}
Output
Check condition in middleware
Middleware can also be used to check the condition. Let's understand through an example.
- Route::Get('/{age}',function($age)
- {
- return view('welcome');
- })-> middleware('age');
- <?php
- namespace App\Http\Middleware;
- use Closure;
- class CheckAge
- {
- /**
- * Handle an incoming request.
- *
- * @param
- \Illuminate\Http\Request $request
- * @param \Closure $next
- * @return mixed
- */
- public function handle($request, Closure $next)
- {
- //return "middleware";
- if($request->age>10)
- {
- echo "Age is greater than 10";
- }
- else
- {
- echo"Age is not greater than 10";
- }
- return $next($request);
- }}
Output: