How to create custom middleware to check custom header for REST API in Laravel 5

How to create custom middleware to check custom header for REST API in Laravel 5

In this Laravel 5 PHP Tutorial, I will let you know how to create our own custom middleware to check custom header for the security.

For example, if you want to check whether security key/token exists in the header or not. you can restrict your apis using middleware with some checks.

You need to first create a custom middleware "isAuthorized" by running below artisa command in your application.

php artisan make:middleware isAuthorized

Ok, now you can check in your project path : app/Http/Middleware/isAuthorized.php file

isAuthorized Middleware
<?php

namespace App\Http\Middleware;

use Closure;

class isAuthorized
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {       
        if(isset(getallheaders()['token']) && getallheaders()['token']=="xxxx") {
            return $next($request);
        }else{
            return response()->json(['status' => false,'error' => "Invalid requst"], 503);
        }
        
    }
}

Now I will add this custom middleware in app/Http/Kernel.php file for assign middleware name.


    protected $routeMiddleware = [  
        ...

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

        ...
    ];  

Now you can create a group to apply filters on group of routes instead of specifying the filter on each route, as group allow us to use middleware, namespace etc.

Route::group(array('middleware' => ['isAuthorized']), function ()
{
    Route::get('dashboard','HomeController@dashboard');
});

Phone: (+91) 8800417876
Noida, 201301
sakarya escort akyazı escort arifiye escort erenler escort eve gelen escort ferizli escort geyve escort hendek escort otele gelen escort sapanca escort söğütlü escort taraklı escort
sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort sakarya escort serdivan escort sapanca escort karasu escort hendek escort ankara escort
sakarya escort kızlar sakarya escort kaliteli sakarya escort vip sakarya escort elit sakarya escort bayan sakarya escort adresleri.