Sapnesh Naik
Senior Full Stack Software Developer
Full stack software developer with 6 years of experience building highly scalable web applications using using backend, frontend, and cloud-based technologies.

How to add a Global function in Laravel using Composer?

December 5, 2017
How to add a Global function in Laravel using Composer?

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);

        for($i=0;$i<$length;$i++){
            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 the 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 the Composer to Add a Global Function in Laravel:

  1. Create a Helpers directory in your app directory.

    $mkdir app/Helpers

  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 IND_money_format() to files attribute of autoload property so that it can be automatically loaded by the Composer when your app bootstraps. This is done by the Composer using the PSR-4 auto-loading standard.

    "autoload": {
       "classmap": [
           "database/seeds",
           "database/factories"
       ],
       "psr-4": {
           "App\\": "app/"
       },
       "files": [
          "app/Helpers/Indian_currency_format.php"
       ]
    },
  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!!