How to Format Currency in Laravel [3 Ways]

Here are three ways to format currency in Laravel.

  1. Using PHP’s number_format()
  2. Using Laravel’s Localization
  3. Using third-party package

Diagram

Diagram of Formatting Currency in Laravel [3 Ways]

Method 1: Using PHP’s number_format()

Laravel Framework is built upon PHP language, so you can format currency using PHP’s number_format() function.

To properly integrate number_format(), you need to register the function in AppServiceProvider.php like this:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Blade;

class AppServiceProvider extends ServiceProvider
{
  /**
  * Register any application services.
  *
  * @return void
  */
  public function register()
  {

  }

  /**
  * Bootstrap any application services.
  *
  * @return void
  */
  public function boot()
  {
    Blade::directive('currency', function ($amount) {
      return "<?php echo '$' . number_format($amount, 2); ?>";
    });
  }
}

Now, you can use the @currency directive inside the view file.

<p>@currency(200)</p>

Method 2: Using Laravel’s Localization

Laravel’s localization features allow you to create localized “translation strings” that can also be used for number and currency formatting.

Here is the step-by-step guide.

Step 1: Create a new translation string

You can create a new translation string in resources/lang/en/messages.php (or another appropriate language file):

<?php

return [
  'currency' => 'USD :amount',
];

Step 2: Use the trans or __ function

You can use the trans() or __ to retrieve the translation string and replace the placeholder.

$price = 200.99;
$formatted = trans('messages.currency', ['amount' => number_format($price, 2)]);
echo $formatted;

Method 3: Using Third-Party Packages

There are also several third-party packages available for currency formatting in Laravel.

One of the most used packages is moneyphp/money, which provides advanced money and currency formatting capabilities. You can install it via Composer and use it in your Laravel project.

Summary

Method Description Example Output
number_format() PHP’s built-in function to format numbers. 200.99
Laravel Localization Uses Laravel’s translation strings combined with number formatting. USD 200.99
money_format() Deprecated in PHP 7.4. Formats currency based on locale settings. (Not recommended) USD 200.99
Third-Party Packages Use packages like moneyphp/money for advanced formatting capabilities. Varies by package

That’s all!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.