JsonAttributeCast.php 525 Bytes
<?php

namespace App\Support;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;

class JsonAttributeCast implements CastsAttributes
{

    public function get($model, string $key, $value, array $attributes)
    {
        if (($value = $model->fromJson($value)) && is_string($value)) {
            return NULL;
        }

        return count($value) === 0 ? NULL : $value;
    }

    public function set($model, string $key, $value, array $attributes)
    {
        return is_null($value) ? '{}' : $value;
    }
}