Between a request and a response, middleware acts as a link. It is a type of filtering mechanism. This lesson explains the middleware mechanism in Laravel.
Laravel verifies user and application authentication if the user is authenticated redirect successfully otherwise if not authenticate then not redirect.
*Middleware Create Command :
php artisan make:middleware <middleware-name>
<middleware-name> Here write you middleware name
After creating middleware you will find it at app/Http/Middleware directory.
Following the example and understand the tutorial middleware mechanism
Step 1 : We create admin middleware , let us know our middleware create command
Php artisan make:middleware adminMiddleware.
Step 2 :after create middleware successfully , you will receive following output
Step 3 : AdminMiddleware will be created at app/Http/Middleware. The newly created file will have the following code already created for you.
<?php
namespace App\Http\Middleware;
use Closure;
class AdminMiddleware {
public function handle($request, Closure $next) {
return $next($request);
}
}
The following is the code for app/Http/Kernel.php −
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel {
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
Admin=> \App\Http\Middleware\AdminMiddleware::class,
];
}
Step 4: Declare middleware
Route::get('/', function () {
//
})->middleware('web');
Route::middleware(['web'])->group(function () {
//
});