How To Fix Cross Site Scripting Vulnerability In Laravel

Hello Artisan,

How to create middleware for XSS protection in Laravel application is going to be today's tutorial. If you would like to protect sql injection in laravel applications, then it is necessary to enable XSS protection in your laravel app.

This laravel XSS protection example teaches you that how we can create our own custom middleware to protect our Laravel application from hackers. So if you don't know how to fix cross-site scripting vulnerability in PHP Laravel, then this example is for you.

So no need how to detect SQL injection, rather we will create a middleware that will be able to sanitize input field requests. You can say that this is the laravel security best practice as a developer.

So let's create and use XSS middleware to protect cross-site scripting vulnerability in Laravel:


Step 1: Create Middleware

In the first step, we need to create XSS middleware for protecting cross-site scripting vulnerability. To create it and update it like below:


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


Step 2: Register Middleware

Now we need to register this newly created middleware like below before using it:


 protected $routeMiddleware = [
  'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
   'XSS' => \App\Http\Middleware\XSS::class,


Now just use it in your route like:


Route::group(['middleware' => ['XSS']], function () {
 Route::get('/home', 'HomeController@index')->name('home');


Read also: Example of Sending SMS to Mobile with Nexmo in Laravel


Hope it can help you.


#laravel #laravel-8x #laravel-security