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 post we will give you information about How to create custom middleware to check custom header for REST API in Laravel 5. Hear we will give you detail about How to create custom middleware to check custom header for REST API in Laravel 5And how to use it also give you demo for it if it is necessary.

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 AppHttpMiddleware;

use Closure;

classisAuthorized
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure  $next
     * @return mixed
     */
    publicfunctionhandle($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' => AppHttpMiddlewareisAuthorized::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');
});

//how-to-set-custom-header-authorization-in-php-curl

Label :

PHP

Object Oriented Programming

Laravel PHP Framework

MVC

Web Development

Hope this code and post will helped you for implement How to create custom middleware to check custom header for REST API in Laravel 5. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

Leave a Comment

Your email address will not be published. Required fields are marked *

43  +    =  51

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US