XSS (Cross-Site Scripting) Protection In Laravel

In this tutorial, I will give you an example of “How to use (Cross-Site Scripting) Protection In Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, laravel 8, and laravel 9 application.

First, what we’re doing here, This is the example :

xss protection in laravel

Before:-

XSS (Cross-Site Scripting) Protection In Laravel

After:-

XSS (Cross-Site Scripting) Protection in Laravel

Imagine you have a register and comment section in your laravel application, in this section anyone can type a comment and register with some script tag and other hacking script tags our application does not check the script and the tags using the scripts anyone can store the script in our database, This term is called XSS attack.

If you have e-Commerce and blog submission sites, anyone can drop his script on login and register, So we will prevent this by using middleware and removing all the tags and script whenever the user can register and post a comment.

Create a Middleware

php artisan make:middleware Xss

app\Http\Middleware\Xss.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class Xss
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $input = $request->all();
        array_walk_recursive($input, function(&$input){
            $input = strip_tags($input);
        });
        $request->merge($input);
        return $next($request);
    }
}

Update Kernel File :

We need to update your Kernel.php file inside the same App/Http/Middleware directory where we need to add the middleware name as shown below.

Related article: How to Prevent Back Button After Logout in Laravel 8.

app\Http\Kernal.php

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

    ];

routes\web.php

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

Route::view('/register','user.register')->name('user.register');
Route::post('/store-register', [UserController::class, 'userRegiter'])->name('store.register');

});

In this article, we learned “How to prevent XSS attack in Laravel”, I hope this article will help you with your Laravel application Project.

Read also:- Laravel Blade components.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com