Skip to content

Instantly share code, notes, and snippets.

@dividy
Last active July 8, 2021 08:46
Show Gist options
  • Save dividy/e5185c098ed8bc6bb518f6239f1f08f0 to your computer and use it in GitHub Desktop.
Save dividy/e5185c098ed8bc6bb518f6239f1f08f0 to your computer and use it in GitHub Desktop.
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class ReadableNumber implements CastsAttributes
{
/**
* 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 get($model, $key, $value, $attributes)
{
return (isset($value) ? number_format($value, 2, ',', ' ') : null);
}
public function set($model, $key, $value, $attributes)
{
return [ $key => str_replace(" ", "", str_replace(",", ".", $value)) ];
}
}
@dividy
Copy link
Author

dividy commented Jul 2, 2021

Usage in model:

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'price' => ReadableNumber::class
    ];

In your migration :

$table->decimal('price', 12, 2)->default(0);

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