Create Custom Middleware (Cmd)
We have to create custom middleware using the laravel command.
So let’s open your terminal and run bellow command:
php artisan make:middleware <middleware-name>
php artisan make:middleware CheckType
CheckType is name of middleware.
After the above run command, you will find one file on bellow location and you have to write the following code:
Location:- Root/app/Http/Middleware/CheckType.php
<?php
namespace App\Http\Middleware;
use Closure;
class AgeMiddleware {
public function handle($request, Closure $next) {
return $next($request);
}
}
Registering Middleware
We need to register each and every middleware before using it. There are two types of Middleware in Laravel.
- Global Middleware -These run on every HTTP request to your application. You can add them to the $middleware property of the app/Http/Kernel.php file.
protected $middleware = [
// Other middleware...
\App\Http\Middleware\MyMiddleware::class,
];
- Route Middleware - These are assigned to specific routes or groups of routes. You can add them to the $routeMiddleware property of the app/Http/Kernel.php file.
protected $routeMiddleware = [
// Other middleware...
'my.middleware' => \App\Http\Middleware\MyMiddleware::class,
];
Add Middleware in Route
Now we will create a simple route using CheckType middleware. So let’s simply open the routes.php file and add those routes.
Location:- Root/routes/web.php
Route::get("check-md",["uses"=>"HomeController@checkMD","middleware"=>"checkType"]);
Add Controller Method
Now at last we have to add a new controller method checkMD() in your Home Controller. So let’s add the “checkMD()” method on the HomeController.php file.
Location:- Root/app/Http/Controllers/HomeController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public function checkMD()
{
dd('checkMD');
}
}
Ok, now we are ready to run our example, so you can run the below links and check how custom helper works.