Laravel - Blade Templates - Custom Echo Handlers

If you attempt to "echo" an object using Blade, the object's __toString method will be invoked. The __toString method is one of PHP's built-in "magic methods". However, sometimes you may not have control over the __toString method of a given class, such as when the class that you are interacting with belongs to a third-party library.

In these cases, Blade allows you to register a custom echo handler for that particular type of object. To accomplish this, you should invoke Blade's stringable method. The stringable method accepts a closure. This closure should type-hint the type of object that it is responsible for rendering. Typically, the stringable method should be invoked within the boot method of your application's AppServiceProvider class:

    use Illuminate\Support\Facades\Blade;
    use Money\Money;
     * Bootstrap any application services.
     * @return void
    public function boot()
        Blade::stringable(function (Money $money) {
            return $money->formatTo('en_GB');

Once your custom echo handler has been defined, you may simply echo the object in your Blade template:

    Cost: {{ $money }}