How to display 1000 as 1k in laravel?

Member

by deron , in category: PHP Frameworks , 3 months ago

How to display 1000 as 1k in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by scotty_walker , 3 months ago

@deron 

You can achieve this by creating a Blade directive in Laravel. Here's an example of how you can create a custom Blade directive to display numbers in a human-readable format:

  1. Open your AppServiceProvider.php file located in app/Providers directory.
  2. Add the following code to the boot() method:
1
2
3
4
5
use IlluminateSupportFacadesBlade;

Blade::directive('formatNumber', function ($expression) {
    return "<?php echo number_format($expression, 0, '', '') >= 1000 ? number_format($expression/1000, 1) . 'k' : number_format($expression); ?>";
});


  1. Then, in your Blade template file, you can use the @formatNumber directive to format the number as follows:
1
{{ @formatNumber($number) }}


Replace $number with the variable containing the number you want to format. This directive will display numbers greater than or equal to 1000 as 1k.


After implementing the Blade directive, you can now use @formatNumber(1000) in your Blade templates to display 1000 as 1k.