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

By Hardik Savani | January 20, 2016 | | 24953 Viewer| Category : Laravel

In Laravel 5 REST API project sometime we need to create create our own custom header for security. like : 'X-hardik':'123456'. this was example, that means in your current project your every request with pass your own custom header like i give you example.this custom header can improve your security. we can also check your header is right or wrong.example :

Your Jquery or AngularJS Request


type: 'POST',

dataType: 'json',

url: 'http://test.hd/api/login',

headers: { 'X-hardik': '123456'},

data: {'email':'','password':'123456'}


alert('Login Successfully');

}).fail(function(jqXHR, ajaxOptions, thrownError){



This is your normal Jquery request with custom header 'X-hardik' and password '123456'.

Now How to check this request in your laravel project.

first fire this command and create middleware.

php artisan make:middleware checkHeader

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

add content on that file.

namespace App\Http\Middleware;

use Closure;

use Illuminate\Contracts\Auth\Guard;

use Response;

class checkHeader



* The Guard implementation.


* @var Guard



* Handle an incoming request.


* @param \Illuminate\Http\Request $request

* @param \Closure $next

* @return mixed


public function handle($request, Closure $next)



return Response::json(array('error'=-->'Please set custom header'));


if($_SERVER['HTTP_X_HARDIK'] != '123456'){

return Response::json(array('error'=>'wrong custom header'));


return $next($request);



Now you have to add in app/Http/Kernel.php file for assign middleware name.

namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel



* The application's global HTTP middleware stack.


* @var array


protected $middleware = [









* The application's route middleware.


* @var array


protected $routeMiddleware = [

'auth' =--> \App\Http\Middleware\Authenticate::class,

'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,

'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

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



Ok now you can use in your route like this way :

Route::post('api/login', array('uses' => 'APIAuthController@login','middleware' => ['checkHeader']));

Try this...