How to add a Global function in Laravel using Composer?

Full Article :

KernalDev -

I recently posted an article explaining how to format a number to Indian Rupee format in PHP / Laravel,  Now this function like any other PHP class can be used inside a Laravel project by manually importing and name-spacing it in a class but it would be accessible only in the class you are using it. Today I will show you how to add any function as a global function in Laravel so that you may access it in any of the class or Controller or View you require.

The Function which we are going to make global in Laravel:

    function IND_money_format($number){    	
        $decimal = (string)($number - floor($number));
        $money = floor($number);
        $length = strlen($money);
        $delimiter = '';
        $money = strrev($money);
            if(( $i==3 || ($i>3 && ($i-1)%2==0) )&& $i!=$length){
                $delimiter .=',';
            $delimiter .=$money[$i];
        $result = strrev($delimiter);
        $decimal = preg_replace("/0./i", ".", $decimal);
        $decimal = substr($decimal, 0, 3);
        if( $decimal != '0'){
            $result = $result.$decimal;
        return $result;

This function basically takes a number as input and returns the result as a string formatted to Indian Rupee format. See this article for more details on how this function works. Now let us see how we can add this as a global function in Laravel

Using composer to add a global function in Laravel:

  1. Create a Helpers directory in your app directory.
    $mkdir app/Helpers

    It is a common practice in Laravel to create a Helpers directory in order to store all your custom classes and such functions which might not be appropriate in a Controller or View.

  2. Copy the IND_money_format() into a Indian_currency_format.php or you can also download the Indian_currency_format.php from my GitHub Gist and save it to Helpers directory.
  3. In your composer.json file add Indian_currency_format.php to files attribute of autoload property so that it can be automatically loaded by composer when your app bootstraps. This is done by composer using PSR-4 auto-loading standard.
    "autoload": {
            "classmap": [
             "psr-4": {
                  "App": "app/"
             "files": [


  4. Finally run composer dump-autoload to refresh the autoload cache.


Now you can use Indian_currency_format() function in any of your Controllers, Views or even custom classes!.

What do you think? Please share your thoughts or ask any questions you might have in the comment section below!!

The post How to add a Global function in Laravel using Composer? appeared first on KernelDev.

Leave a Comment

%d bloggers like this: