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.
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.
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.
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.
Removes extra or non-useable attributes from request data.
Run the command below to install the package:
composer require touhidurabir/laravel-model-sanitize
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()
.$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.