An Eloquent base model that automatically sanitizes specified attributes on get and set, protecting your application from XSS vulnerabilities out of the box.
- Automatically purifies HTML on both read (
getAttribute) and write (setAttribute) - Powered by stevebauman/purify (HTMLPurifier wrapper)
- Zero-configuration: just list the attributes to sanitize
- Supports Laravel 9, 10, 11, 12, and 13
- Supports PHP 8.1, 8.2, 8.3, and 8.4
| Dependency | Version |
|---|---|
| PHP | ^8.1 | ^8.2 | ^8.3 | ^8.4 |
| Laravel | ^9.0 | ^10.0 | ^11.0 | ^12.0 | ^13.0 |
| stevebauman/purify | ^6.3 |
composer require redaelfillali/laravel-secure-modelThe service provider is registered automatically via Laravel's package auto-discovery.
Optionally publish the Purify configuration to customise the HTML rules:
php artisan vendor:publish --provider="Stevebauman\Purify\PurifyServiceProvider"Extend SecureModel instead of the default Eloquent Model and declare the attributes you want automatically sanitized in the $sanitizeAttributes array:
<?php
use Redaelfillali\LaravelSecureModel\SecureModel;
class Post extends SecureModel
{
// These attributes will be purified on every get and set
protected array $sanitizeAttributes = ['title', 'body', 'excerpt'];
}That's it — any XSS payloads stored in or read from the listed attributes will be stripped automatically:
$post = new Post();
$post->body = '<p>Hello</p><script>alert("xss")</script>';
// The <script> tag is stripped; safe HTML is preserved.
echo $post->body; // <p>Hello</p>Attributes not listed in $sanitizeAttributes are left completely untouched, so only the fields you care about are affected.
SecureModel overrides two Eloquent methods:
| Method | Behaviour |
|---|---|
setAttribute($key, $value) |
Sanitizes the value before it is stored in the model's attribute bag |
getAttribute($key) |
Sanitizes the value when it is retrieved from the model |
Only attributes listed in $sanitizeAttributes and whose value is a string are passed through Purify::clean(). All other types (int, null, arrays …) are returned as-is.
composer testTests are written with Pest and use Orchestra Testbench for a full in-process Laravel environment.
The MIT License (MIT). See LICENSE for details.