Code Monkey home page Code Monkey logo

model-json-attribute-guard-laravel's Introduction

JSON Column Guard

This package allows validation and custom casts for JSON columns.

Have you ever tried to use a json column, and:

  1. Validating schema of the column was difficult or messy
  2. Querying the column was onerous
  3. 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:

  1. Can you enforce each key is valid?
  2. Can you enforce the two dates are valid dates?
  3. 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.

<?php
namespace App\Models\User;

use Zschuessler\ModelJsonAttributeGuard\JsonAttributeGuard;

class PreferencesJsonColumn extends JsonAttributeGuard
{

    public function schema() : array
    {
        return [
            // Use wildcard syntax to apply rules to all children
            '*.name'           => 'required',
            '*.value'          => 'required|min:3',
            '*.date_created'   => 'present|nullable|date',
            '*.date_updated'   => 'present|nullable|date',
        ];
    }
}

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:

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\User\PreferencesJsonColumn;
use Zschuessler\ModelJsonAttributeGuard\Traits\HasJsonAttributeGuards;

class User extends Model
{
    use HasJsonAttributeGuards;

    public $casts = [
        'preferences' => PreferencesJsonColumn::class
    ];

Step 3: Success

This code will work wonderfully:

$user->preferences = [
    [
        'name' => 'Favorite Band',
        'value' => 'Slenderbodies',
        'date_created' => '2019-09-15',
        'date_updated' => '2020-01-01'
    ]
];
$user->save();

Great! But the code below will throw a JsonAttributeValidationFailedException exception - oh no! Your model won't be saved.

$user->preferences = [
    'name' => null,
    'value' => null,
    'date_created' => null,
    'date_updated' => null,
];
$user->save();

This was a simple example. The possibilities are endless!

model-json-attribute-guard-laravel's People

Contributors

zschuessler avatar

Stargazers

 avatar

Watchers

 avatar

Forkers

engagedc

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.