Created
May 9, 2020 02:15
-
-
Save maxwellimpact/fa6a26bff72e522f66816f37f1768364 to your computer and use it in GitHub Desktop.
Extends CastsAttributes specifically for creating models derived from JSON fields.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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([]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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