Sabbir Ahmed

Sabbir Ahmed

1 month ago

Boost Your Laravel Workflow: Craft Custom Helper Functions

Laravel helper function always provides us a convenient development experience. Helper functions are global, you can always run your logic given in this function from anywhere. You just have to call this function. For example, you might always use dd() function whenever you need to debug a step. Along with the built in helper functions provided by laravel, we can also create your own custom helper functions. In this article, we will see how we can achieve that. 

Create helper file


Lets say, we will use a function named customFunction() as a helper. Now, lets create a file named CustomHelper.php under app/Helpers/CustomHelper.php:

<?php

// app/Helpers/CustomHelper.php

if (!function_exists('customFunction')) {
    function customFunction($parameter)
    {
        // Your custom logic here
        return $parameter;
    }
}

You will have to provide the logics in this function scope. 

Register your file and run autoload


After creating the helper file, you need register the file in composer.json: 

"autoload": {
    "files": [
        "app/Helpers/CustomHelper.php"
    ],
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},

Then, please run this command: 


composer dump-autoload

Use the function


Done, you have created your own custom helper function. Now you can call the function from anywhere of your application like this: 

customFunction()

Helper functions make your workflow very convenient and faster, additionally it helps you to get rid of excess codings. Please give a try with this way if you havent created your own helpers.

Hope you have found this article useful. Please provide a love to this article and let me know your thoughts in the comments below. 

Wish you a great day. 

Comments

Login As User
Word Count: 0