20.4 C
New York
Sunday, April 2, 2023

How to create middleware for XSS protection in 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 AppHttpMiddleware;

use Closure;

use IlluminateHttpRequest;

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' => AppHttpMiddlewareAuthenticate::class,


'XSS' => AppHttpMiddlewareXSS::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', 'CustomValDemoController@customVali');

Route::post('customValiPost', 'CustomValDemoController@customValiPost');


Related Articles

Latest Articles