Skip to content

Instantly share code, notes, and snippets.

@maxwellimpact
Created May 9, 2020 02:15
Show Gist options
  • Save maxwellimpact/fa6a26bff72e522f66816f37f1768364 to your computer and use it in GitHub Desktop.
Save maxwellimpact/fa6a26bff72e522f66816f37f1768364 to your computer and use it in GitHub Desktop.
Extends CastsAttributes specifically for creating models derived from JSON fields.
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
abstract class CastsJsonAttributes implements CastsAttributes
{
abstract public function createModel(array $data);
public function get($model, string $key, $value, array $attributes)
{
$data = json_decode($value, true);
return $this->createModel($data ?? []);
}
public function set($model, string $key, $value, array $attributes)
{
if (is_array($value)) {
return json_encode($value);
}
return $value ? $value->toJson() : json_encode([]);
}
}
<?php
namespace App\Casts;
use App\JsonModel;
class JsonToCollectionCast extends CastsJsonAttributes
{
public function createModel(array $data)
{
return collect($data)->map(fn($attributes) => new JsonModel($attributes));
}
}
<?php
namespace App\Casts;
use App\JsonModel;
class JsonToModelCast extends CastsJsonAttributes
{
public function createModel(array $data)
{
return new JsonModel($data);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment