judahnator/laravel-json-manipulator

An extension to the judahnator/json-manipulator library for Laravel

v3.0.1 2021-01-21 15:52 UTC

This package is auto-updated.

Last update: 2024-03-22 06:59:38 UTC


README

pipeline status coverage report

What?

This is an extension to my other json-manipulator library. Go read the docs for that if you want to know the details.

The basics of why this exists is Laravel provides access to JSON columns via PHP overloading, meaning you cannot directly interact with the data as if it were a native PHP object.

This library fixes that problem by providing a trait you can use in your models. By dropping in accessors for the fields you wish to manipulate you can more easily work with the data.

Installation:

Via composer:

composer require judahnator/laravel-json-manipulator

Usage:

Usage is super easy.

  1. At the top of your models, you need to use HasJsonAttributes;.
  2. For each of your JSON attributes, you need to write an accessor.
    1. For JSON objects: return $this->load_json_object();
    2. For JSON arrays: return $this->load_json_array();

If your accessor name is not a field in your database, or you wish to reference a custom attribute, you may pass in an attribute to name to use.

You may also pass in an optional second attribute to set what your default value should be if the attribute does not exist yet on the model.

return $this->load_json_object(
    'my_custom_attribute_name', 
    '{"with a": "custom default"}'
);

Example:

Say you have a "Friend" model.

Your friend has multiple contact methods which are stored as an object. The field could be named contact_methods in your database.

{
  "email": "friend@example.com",
  "mobile": "208-555-1234"
}

Your friend also has an array of favorite foods. Say they were stored as favorite_foods in your database.

[
  "Pizza",
  "Celery",
  "Apple"
]

With the above, your model might look something like this.

<?php

use \Illuminate\Database\Eloquent\Model;
use judahnator\JsonManipulator\JsonArray;
use judahnator\JsonManipulator\JsonObject;
use judahnator\LaravelJsonManipulator\HasJsonAttributes;

class Friend extends Model
{
    use HasJsonAttributes;
    
    /**
     * Accessor to return the contact_methods attribute
     * @return JsonObject
     */
    public function getContactMethodsAttribute(): JsonObject
    {
        return $this->load_json_object();
    }
    
    /**
     * Accessor to return the favorite_foods attribute
     * @return JsonArray
     */
    public function getFavoriteFoodsAttribute(): JsonArray
    {
        return $this->load_json_array();
    }
}

You may now use those fields on your model just like you would use any other native PHP array or object.

<?php
$friend = Friend::find('Judah');
$friend->contact_methods->mastodon = 'judahnator@mastodon.xyz';
$friend->favorite_foods[] = 'cake';
unset($friend->favorite_foods[1]); // nobody likes celery
$friend->save();