redaelfillali / laravel-secure-model
Eloquent base model with auto-sanitized getters and setters.
Package info
github.com/redafillali/laravel-secure-model
pkg:composer/redaelfillali/laravel-secure-model
Requires
- php: ^8.1|^8.2|^8.3|^8.4
- illuminate/database: ^9.0|^10.0|^11.0|^12.0|^13.0
- illuminate/support: ^9.0|^10.0|^11.0|^12.0|^13.0
- stevebauman/purify: ^6.3
Requires (Dev)
- orchestra/testbench: ^7.0|^8.0|^9.0|^10.0|^11.0
- pestphp/pest: ^2.0|^3.0
- pestphp/pest-plugin-laravel: ^2.0|^3.0
README
An Eloquent base model that automatically sanitizes specified attributes on get and set, protecting your application from XSS vulnerabilities out of the box.
Features
- 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
Requirements
| 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 |
Installation
composer require redaelfillali/laravel-secure-model
The 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"
Usage
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.
How it works
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.
Testing
composer test
Tests are written with Pest and use Orchestra Testbench for a full in-process Laravel environment.
License
The MIT License (MIT). See LICENSE for details.