Download the PHP package zschuessler/model-json-attribute-guard-laravel without Composer
On this page you can find all versions of the php package zschuessler/model-json-attribute-guard-laravel. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download zschuessler/model-json-attribute-guard-laravel
More information about zschuessler/model-json-attribute-guard-laravel
Files in zschuessler/model-json-attribute-guard-laravel
Package model-json-attribute-guard-laravel
Short Description An intuitive and fun way to bring consistency to your json columns
License LGPL-2.1-only
Informations about the package model-json-attribute-guard-laravel
JSON Column Guard
This package allows validation and custom casts for JSON columns.
Have you ever tried to use a json column, and:
- Validating schema of the column was difficult or messy
- Querying the column was onerous
- Casting types when saving models wasn't fun
Well now you can rest easy!
Example
You want to save user preferences. It's highly dynamic data, so you throw it into a json column:
Database Table | Database Column | Desired Schema |
---|---|---|
users | preferences |
[
{
"name": "Favorite Band",
"value": "Slenderbodies",
"date_created": "2019-09-15",
"date_updated": "2020-01-01"
}
]
|
Here are problems:
- Can you enforce each key is valid?
- Can you enforce the two dates are valid dates?
- What about always ensuring the column is an array, regardless if a preference exists or not?
We can.
Step 1: Create The Validator Class
Let's use Laravel's own Validator syntax to describe what we want.
Under the hood Laravel's Validators are used: you can use any rule you want. Go nuts.
Step 2: Add a trait and cast to your Model
Let's tell Laravel we want our model to do a custom cast:
Step 3: Success
This code will work wonderfully:
Great! But the code below will throw a JsonAttributeValidationFailedException
exception - oh no! Your model won't be saved.
This was a simple example. The possibilities are endless!