Skip to content

Instantly share code, notes, and snippets.

@m-ostadi
Last active October 7, 2021 17:57
Show Gist options
  • Save m-ostadi/acec4b9e2af7e76686e86ef096a8a51c to your computer and use it in GitHub Desktop.
Save m-ostadi/acec4b9e2af7e76686e86ef096a8a51c to your computer and use it in GitHub Desktop.
Laravel eloquent cast for partial updating JSON fields
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class PartialUpdateJson implements CastsAttributes
{
/**
* Cast the given value.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return array
*/
public function get($model, $key, $value, $attributes)
{
return json_decode($value, true);
}
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param array $value
* @param array $attributes
* @return string
*/
public function set($model, $key, $value, $attributes)
{
return json_encode($value + ($model[$key]??[]));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment