Guide For Creating Your Own PHP Helpers In Laravel Project

Sometimes it becomes difficult to call codes again and again which also appears out to be hectic while web development. That is the reason and that is why being a developer you always require an easy function which can be repeated under every class. As similar in PHP that the number_format function is easy to use and can also be called in every PHP file or class in your Laravel project. But when you require the whole format of numbers, writing the same numbers back to back becomes a big pain.

To get rid of this pain, Laravel development services has found an in-built helper which are capable to create your own helper. Let’s get started.

  • Create a PHP File

Under the directory of your desire, create a Helper.php file.

<?php

/**
* change plain number to formatted currency
*
* @param $number
* @param $currency
*/
function formatNumber($number, $currency = 'IDR')
{
if($currency == 'USD) {
return number_format($number, 2, '.', ',');
}
return number_format($number, 0, '.', '.');
}

It’s that much simple as shown above. As per as your need, you can write another function to helper file. You can even use Laravel Facade or any class under Laravel helper function.

  • Autoload Composer

When you are done creating with the helper, all you need to register helper file to the composer.json, or else Laravel will not identify the file. Consider adding Files array under autoload segment.

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

After it, run the function with:

composer dumpautoload

  • Utilization Of Helper Function

Now, the helper is autoloaded and is now ready to be used immediately through calling the function in any class.

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

Or,

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

Simple enough right! But always keep in mind that if your function’s behavior is complex or require to handle class dependencies, then prefer creating your own class instead of a helper function. And still, you find any difficulties while creating a helper function, consider hiring a Laravel development company to cover all your requirement of web development.

Leave a comment