How To Create Helper Functions in Laravel

Didik Tri Susanto
Teknomuslim
Published in
2 min readApr 1, 2017
credit: http://www.interactivewest.com/images/Service_pages/service_page-programming.png

When our code becomes complex, sometime we need simple function which callable in every single class or even in our view that we’ve been created.

For example, we need a function to create custom number format based on currency. In PHP it is easy to use number_format function, and it’s also callable in every class or PHP file in your Laravel project. But when we need include some logic to build and return your formatted number, then it will becomes pain to write same logic every time just to get formatted number.

Let’s create a helper!

Laravel has many built in helpers as you can read in docs, but don’t find a suited one to our case, so we have to create our own helper.

Create simple PHP file.

Create Helper.php inside app directory or wherever directory you want. For example I wrote function to format number by currency:

Yup, just simple as that. You may write another function to helper file as you need. Also we can use Laravel Facade or any class in Laravel inside helper function.

Autoload Composer

After we created our helper, Laravel won’t recognize our file so we need to register helper file to our composer.json. Add Files array inside autoload section. It may look like this:

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

Then don’t forget to run

composer dumpautoload

Using helper function

Our helper is autoloaded now, so we should be able to use our helper immediately. Just call our function in any class

$price = formatNumber($data->price, ‘IDR’);

or in blade view

{{ formatNumber($data->price, ‘IDR’) }}

Conclusion

We may wrote many helper functions to simplify our code. But remember if your function has complex behavior or need to manage class dependencies, then we should create own class rather than helper function.

Happy Coding, Folks!

--

--

Didik Tri Susanto
Teknomuslim

Proud to be Moslem | Introvert | Backend Engineer | Laravel Developer