Hasan Setiawan

Write, write, write give your wings on code!

Follow me on GitHub

Laravel helper creation

When we doing development in Laravel, sometime we need a helper. Let say we need a number format. First thing you need to do is create a folder Helpers inside app directory. Then put a new numberHelper.php file inside it. Then add this code:

              
if (!function_exists('numberFormatHelper')) {
    function numberFormatHelper($number)
    {
        return number_format($number, 2, ".", ",");
    }
}
              
            

Next thing is make it accesable anywhere, by load it using composer auload. Open your composer.json file, then find the autoload code block.

              
          "autoload": {
            // Call your file helper code here, put it inside files object key:
                "files": [
                    "app/Helpers/numberHelper.php"
                ],
                "classmap": [
                    "database/seeds",
                    "database/factories"
                ],
                "psr-4": {
                    "App\\": "app/"
                }
            },
          
          

Run command composer dump-autoload by hit this command compoer du. Now you can access your function helper anywhere by call function directly numberFormatHelper(2000.987). Will return 2,000.99