Getting Started

For this tutorial, I will create a custom middleware name RegionSevenProvinces.

php artisan make:middleware RegionSevenProvinces

**app/Http/Middleware/RegionSevenProvinces.php **

namespace App\Http\Middleware;

use Closure;

class RegionSevenProvinces
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $arr = [
            'Bohol',
            'Cebu',
            'Negros Oriental',
            'Siquijor'
        ];
        if(in_array($request->province,$arr)){
            dd("{$request->province} is in Region 7 province.");
        } else {
            dd("{$request->province} is not in Region 7 province.");
        }
        return $next($request);
    }
}

My sample middleware logic is that I declare the four Region 7 provinces in an array. Then I have an if else statement to check if the request province is in Region 7 or not.

app/Http/Kernel.php

 'RegionSevenProvinces' => \App\Http\Middleware\RegionSevenProvinces::class,

Register the middleware in Kernel file. Put it in protected $routeMiddleware.

**app/Http/Controllers/ProvinceController.php **

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Middleware\RegionSevenProvinces;

class ProvinceController extends Controller
{
     public function __construct()
    {
       $this->middleware('RegionSevenProvinces');
    }

    public function province()
    {
        
    }
}

We registered our middleware inside our controller.

**routes/web.php **

Route::get('region-seven-provinces', 'ProvinceController@province')
->middleware('RegionSevenProvinces');

Define the middleware directly to the routes.

**Sample Output: **

Alt TextAlt Text