Add support for casting to Decimal via cast table#3
Add support for casting to Decimal via cast table#3AJenbo wants to merge 2 commits intophp-decimal:masterfrom
Conversation
|
Thank you for this PR, I think this is a good idea.
|
|
Thanks for explaining that. I have adjusted things to instead use the trait as that turned out to be the most sensible way to implement the suggestions. This has the benefit of the trait now handling casting both to and from the string representation Mode: <?php
namespace App;
use Decimal\Decimal;
use Decimal\DecimalObjectCast;
/**
* @property Decimal $value
*/
class Item extends Model
{
use DecimalObjectCast;
protected $casts = [
'oldValue' => 'decimal:2', // Laravel format, will default to Decimal::DEFAULT_PRECISION
'value' => 'decimal:2:8', // Extended format with precision
];
} |
|
I made the format |
|
After tresting things a bit I found that it could actually be done a bit simpler. Now the only overwrites are for @rtheunissen any feedback? |
|
I've been away on vacation but I've been thinking about this work and I think overall it is a good idea that I'll take a closer look at this week and merge. |
|
As of Laravel 7, the recommended way to perform custom casting is via a Cast class (https://laravel.com/docs/10.x/eloquent-mutators#custom-casts). You can still pass parameters to these, but it would likely be slightly 'safer' than using a trait to override the cast method. Example usage: <?php
namespace App;
use Decimal\Decimal;
use Decimal\DecimalObjectCast;
/**
* @property Decimal $value
*/
class Item extends Model
{
use DecimalObjectCast;
protected $casts = [
'oldValue' => DecimalObjectCast::class.':2', // Laravel format, will default to Decimal::DEFAULT_PRECISION
'value' => DecimalObjectCast::class.':2:8', // Extended format with precision
];
} |
First of thanks for a nice extensions 👍
The idea here is to make it easy for developers to use the Decimal class directly on models rather then having to implement mutators for every attribute.
This also extends the format to allow for providing the precision value in the cast string