---
description: >-
  https://www.itsolutionstuff.com/post/laravel-57-middleware-tutorial-with-exampleexample.html
---

# Laravel 5.7 Middleware Tutorial With Example (ok)

![](https://1592565776-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-LVfVRgKBlsVnWvhnDaa%2Fuploads%2FxdsKzPmpIXmOqD9KRuBo%2FScreenshot_4.png?alt=media\&token=4fde811e-1447-4f61-9635-087320246e37)

C:\xampp\htdocs\reset\routes\web.php

```
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
 */
use App\Http\Controllers\HomeController;
Route::get('/', function () {
  dd('Welcome to simple user route file.');
});
// Route::get("check-md", ["uses" => "HomeController@checkMD", "middleware" => "checkType"]);
// ==
Route::get('/check-md', function () {
  echo "Test 1...";
})->middleware('checkType');
// ==
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
```

C:\xampp\htdocs\reset\app\Http\Kernel.php

```
<?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<int, class-string|string>
   */
  protected $middleware = [
    // \App\Http\Middleware\TrustHosts::class,
    \App\Http\Middleware\TrustProxies::class,
    \Fruitcake\Cors\HandleCors::class,
    \App\Http\Middleware\PreventRequestsDuringMaintenance::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<string, array<int, class-string|string>>
   */
  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' => [
      // \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
      'throttle:api',
      \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],
  ];
  /**
   * The application's route middleware.
   *
   * These middleware may be assigned to groups or used individually.
   *
   * @var array<string, class-string|string>
   */
  protected $routeMiddleware = [
    ...
    'checkType'        => \App\Http\Middleware\CheckType::class,
  ];
}
```

C:\xampp\htdocs\reset\app\Http\Middleware\CheckType.php

```
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
class CheckType {
  /**
   * Handle an incoming request.
   *
   * @param  \Illuminate\Http\Request  $request
   * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
   * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
   */
  public function handle(Request $request, Closure $next) {
    if ($request->type != 2) {
      return response()->json('Please enter valid type');
    }
    return $next($request);
  }
}
```

##

## Laravel 5.7 Middleware Tutorial With Example

By Hardik Savani February 8, 2019 Category : PHP Laravel![](https://a.vdo.ai/core/assets/img/cross.svg)PlayUnmuteLoaded: 1.00%Fullscreen[![VDO.AI](https://a.vdo.ai/core/assets/img/logo.svg)](https://vdo.ai/?utm_medium=video\&utm_term=itsolutionstuff.com\&utm_source=vdoai_logo)Today, i will share with you how to create custom middleware in laravel 5.7 application. i write step by step tutorial of use of middleware in php laravel 5.7 project. you will understand how to protect your site using middleware in laravel 5.7.

you can see default auth middleware in laravel 5.7. auth middleware will protect your route url, allow only logged in user in laravel 5.7.

a middleware are used for filter HTTP requests in your web application. One of the basic requirement of any web application is HTTP requests filter, so we have to make is well for example make auth middleware. auth middleware always check if you are going then and then you can access those page.

In this example, i am going to create "checkType" middleware and i will use simply on route, when they route will run you must have to pass "type" parameter with "2" value then and then you can access those request likes.

So just follow few step to create custom middleware.

![](https://www.itsolutionstuff.com/upload/laravel-5-7-middleware-custom.png)

**Step 1: Create Custom Middleware**

In first step, we have to create custom middleware using laravel 5.7 command. So let's open your terminal and run bellow command:

```
php artisan make:middleware CheckType
```

After above run command you will find one file on bellow location and you have to write following code:

**app/Http/Middleware/CheckType.php**

```
<?phpnamespace App\Http\Middleware;use Closure;class CheckType{    /**     * Handle an incoming request.     *     * @param  \Illuminate\Http\Request  $request     * @param  \Closure  $next     * @return mixed     */    public function handle($request, Closure $next)    {        if ($request->type != 2) {            return response()->json('Please enter valid type');        }        return $next($request);    }}
```

After successfully write logic of middleware then we have to register this middleware on kernel file. So let's add bellow changes in your controller file:

**app/Http/Kernel.php**

```
<?phpnamespace App\Http;use Illuminate\Foundation\Http\Kernel as HttpKernel;class Kernel extends HttpKernel{    ....    /**     * The application's route middleware.     *     * These middleware may be assigned to groups or used individually.     *     * @var array     */    protected $routeMiddleware = [        ....        'checkType' => \App\Http\Middleware\CheckType::class,    ];}
```

**Step 2: Add Route**

Now we will create simple route using CheckType middleware. So let's simply open routes.php file and add those route.

**routes/web.php**

```
Route::get("check-md",["uses"=>"HomeController@checkMD","middleware"=>"checkType"]);
```

Read Also: [How to send mail using queue in Laravel 5.7?](https://www.itsolutionstuff.com/post/how-to-send-mail-using-queue-in-laravel-57example.html)

**Step 3: Add Controller Method**

Now at last we have to add new controller method checkMD() in your Home Controller. So let's add checkMD() method on HomeController.php file.

**app/Http/Controllers/HomeController.php**

```
<?phpnamespace 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 bellow links and check how custom helper works.

Read Also: [Laravel 5.7 - QR Code Generator Example](https://www.itsolutionstuff.com/post/laravel-57-qr-code-generator-exampleexample.html)

```
http://localhost:8000/check-md?type=2http://localhost:8000/check-md?type=1
```

I hope it can help you...
