Automatically Sanitize Model Data

Packages

November 11th, 2021

laravel-model-sanitize-featured.png

Laravel Model Sanitize is a package by Touhidur Rahman to handle the sanitization process of model data when creating and updating records.

Given the following call to User::create(), the Sanitize package will remove non-fillable data automatically:

1// Using the package's Sanitizable triat
2use Touhidurabir\ModelSanitize\Sanitizable;
3use Illuminate\Database\Eloquent\Model;
4 
5class User extends Model {
6 use Sanitizable;
7}
8 
9// The trait removes the `data` key, which is not a fillable field
10$data = [
11 'email' => 'somemail@test.com',
12 'password' => 'password',
13 'data' => 'some data' // Invalid field
14];
15 
16User::create($data);

The Sanitizable trait will automatically work for the various create and update model methods (i.e., updateOrCreate, firstOrCreate, etc.).

If you are using $fillable on models, this package will not be necessary, however, if you use $guarded = [], this package will discard columns not found on the table.

The package also has two static methods for separating data with corresponding fields to get valid/invalid data:

1$data = [
2 'email' => 'somemail@test.com',
3 'password' => 'password',
4 'data' => 'some data',
5 'name' => 'Test User'
6];
7 
8// Get only valid fields
9User::sanitize($data);
10/*
11[
12 'email' => 'somemail@test.com',
13 'password' => 'password',
14 'name' => 'Test User'
15]
16*/
17 
18// Get invalid attributes from data
19User::gibberish($data);
20/*
21[
22 'data' => 'some data',
23]
24*/

You can learn more about this package, get full installation instructions, and view the source code on GitHub.


This package was submitted to our Laravel News Links section. Links is a place the community can post packages and tutorials around the Laravel ecosystem. Follow along on Twitter @LaravelLinks

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.