How to sanitize model data in Laravel

What does it mean to sanitize model data?

To sanitize data: The first step is to make the data clean and free of unwanted entries.

Sanitizing data also prevents illegal access to data.

To sanitize model data in this context means to ensure data are passed to their model fillables. To understand this statement, let me explain the $fillable property that Laravel has.

Laravel has a model property called $fillable. This property is set to be protected, and it contains attributes in an array defining the attribute of a table that can be filled.

Example

protected $fillable = ['name','dob']; 

The code above will only allow the model to store data for name and dob. Any other data coming in is not accepted.

Laravel Model Sanitize

In this shot, we would be making use of a package called laravel model sanitize.

This package is used to make data ready for storing/updating into the database.

Benefit of Laravel Model Sanitize

  1. An instance where we have a table with many fillable attributes, our model would have an array containing a long list of fillable attributes when we can call or use a single line to do this.

  2. Removes extra or non-useable attributes from request data.

Package Installation

Run the command below to install the package:

composer require touhidurabir/laravel-model-sanitize

Implementation

To use this package after installation, you will need to add this trait to whichever model you want to sanitize like this:

use Sanitizable; 

This trait supports all methods listed below:

  • updateOrCreate()
  • firstOrCreate()
  • firstOrNew()
  • create()
  • forceCreate()
  • update().

Example

$validated = $request->validated();//passing the input values through validation rules 

$user = User::create($validated);//storing to the database

$profile = $user->profile->create($validated);//storing to the database

The code above will run smoothly instead of throwing an \Illuminate\Database\QueryException error. It will silently remove the non-useable attribute from the requested data if there are any.

Free Resources