Skip to content

Latest commit

 

History

History
45 lines (31 loc) · 1.21 KB

casting.md

File metadata and controls

45 lines (31 loc) · 1.21 KB

🎯 Casting

You can cast your model's field to Money type and next work with the monetary object within your Laravel application.

There's an example:

// app/Models/Product.php

use Illuminate\Database\Eloquent\Model;
use PostScripton\Money\Casts\MoneyCast;

class Product extends Model
{
    // ...
    
    protected $casts = [
        // other casts
        
        'price' => MoneyCast::class,
    ];
}

Now the price attribute will always be a type of Money. Here's how you can use it:

$product = new Product();
// ...

$product->price; // Money instance, for example, $ 120 is set somewhere above
$product->price->divide(2); // sale 50% => $ 60

$commission = money('100000'); // $ 10
$checkout = $product->price->clone()->add($commission); // Money instance, $ 70

Note that you can't just add the commission because it will affect the price field as well, but we want another monetary object to work with it independently. More about cloning you can read here.

More about casting in Laravel you can read in the official documentation.


📌 Back to the contents.