How to create middleware for XSS protection in Laravel?

Today now in this post i will i how to create middleware for XSS protection in laravel. XSS(Cross Site Scripting) protection is must need in our site because if we do not XSS protection then our site is not secure. XSS filter through we can remove the html tag from our input value and also it is very important to remove html tag for the security. In our laravel application we can implement it by using middleware concept in our project. So here i will show you how to create XSS filter middleware in our laravel application by using following step.

At first fire following command and need to create middleware:

Create Middleware

php artisan make:middleware XSS

Then now, we can see new file in app/Http/Middleware/XSS.php and then just put the bellow code in our 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);

Now at last we have to register our middleware in our app/Http/Kernel.php file. and then add the following line in $routeMiddleware array.



Route::group(['middleware' => ['XSS']], function () {
  Route::get('customVali', 'CustomValDemoController@customVali');
  Route::post('customValiPost', 'CustomValDemoController@customValiPost');

Read Also :Laravel Join with Subquery in Query Builder Example

Thanks for read. I hope it help you. For more you can follow us on facebook.


About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →