laravel-money icon indicating copy to clipboard operation
laravel-money copied to clipboard

[8.x] Money object transformed to string during data/props passing in Blade view/components

Open sudkumar opened this issue 1 year ago • 1 comments

First of all, thank you for creating and maintaining this wonderful wrapper for money-php.

Issue Details

When passing Money object as data/props to Blade view/components, the money gets rendered in the transition and the received data is of type "string".

// app/Http/Controllers/QuoteController.php
return view('quote', ['money' => new Money(1000, 'USD')]);

// resources/views/quote.blade.php
{{ gettype($money) }} // this outputs 'string' instead of 'object'

@if ($money->isPositive())
  // The above expression FAILS!
@endif

Why ?

The Money class implements Illuminate\Contracts\Support\Renderable which instructs Laravel to render it during transmission.

https://github.com/cknow/laravel-money/blob/a98ca18f72abb864a39530d81f869494ff22fd83/src/Money.php#L39-L41

Reproduction

Here is a simple minimal reproduction repo I have setup to test the Renderable object passing to view.

Solution

I was wondering why Money implements Renderable interface ?

__toString already allows transformation to strings (with some modifications) which inturn allows {{ $money }} to be used in blade views.

public function __toString () {
-  return $this->render();
+  return $this->format();
}

sudkumar avatar Feb 25 '23 17:02 sudkumar

You are right @sudkumar

ricardogobbosouza avatar Aug 17 '23 13:08 ricardogobbosouza