Last active
October 7, 2021 17:57
-
-
Save m-ostadi/acec4b9e2af7e76686e86ef096a8a51c to your computer and use it in GitHub Desktop.
Laravel eloquent cast for partial updating 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; | |
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