clrghouz/app/Models/Casts/CollectionOrNull.php

38 lines
847 B
PHP
Raw Normal View History

<?php
2024-11-04 07:25:49 +00:00
namespace App\Models\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
2024-11-04 07:25:49 +00:00
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
class CollectionOrNull implements CastsAttributes
{
/**
* Cast the given value.
*
2024-11-04 07:25:49 +00:00
* @param Model $model
2023-06-27 07:39:11 +00:00
* @param string $key
* @param mixed $value
* @param array $attributes
* @return Collection
*/
2024-11-04 07:25:49 +00:00
public function get(Model $model,string $key,$value,array $attributes): Collection
{
return collect(json_decode($value, true));
}
/**
* Prepare the given value for storage.
*
* @param Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return string|null
*/
2024-11-04 07:25:49 +00:00
public function set(Model $model,string $key,$value,array $attributes): ?string
{
return ($value->count()) ? json_encode($value) : NULL;
}
}