How to create middleware for XSS protection in Laravel?

By Hardik Savani | March 4, 2016 | Category : PHP Laravel

XSS(Cross Site Scripting) protection must need in your site because if you do not XSS protection then your site is not secure. XSS filter through you can remove html tag from your input value and it is very important to remove html tag for security. in your laravel 5.2 application you can implement by using middleware concept in your project. so how to create XSS filter middleware in your laravel application by using following step.

First fire following command and create middleware:

Create Middleware

php artisan make:middleware XSS

Now, you can see new file in app/Http/Middleware/XSS.php and just put bellow code in your XSS.php file.


namespace App\Http\Middleware;

use Closure;

use Illuminate\Http\Request;

class XSS


public function handle(Request $request, Closure $next)


$input = $request->all();

array_walk_recursive($input, function(&$input) {

$input = strip_tags($input);



return $next($request);



At last you have to register your middleware in your app/Http/Kernel.php file. and add following line in $routeMiddleware array.


class Kernel extends HttpKernel



protected $routeMiddleware = [

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


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



Now you are ready to use XSS middleware in your routes.php file, in bellow routes.php file you can that way:


Route::group(['middleware' => ['XSS']], function () {

Route::get('customVali', '[email protected]');

Route::post('customValiPost', '[email protected]');


Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.