Skip to content

Instantly share code, notes, and snippets.

@nasrulhazim
Last active February 21, 2021 03:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasrulhazim/afb21a0051085e75f2592b3a898c7d65 to your computer and use it in GitHub Desktop.
Save nasrulhazim/afb21a0051085e75f2592b3a898c7d65 to your computer and use it in GitHub Desktop.
Cast UUID for MySQL
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class UUID 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 join('-', unpack('H8time_low/H4time_mid/H4time_hi/H4clock_seq_hi/H12clock_seq_low', $value));
}
/**
* 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 pack('H*', str_replace('-', '', $value));
}
}
@nasrulhazim
Copy link
Author

usage:

<?php

namespace App\Models;

use App\Casts\UUID;
use Illuminate\Database\Eloquent\Model;

class Profile extends Model
{
    protected $casts = [
        'uuid' => UUID::class,
    ];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment