How to Create Custom Helper Functions in Laravel
Sometimes you need small reusable functions across your Laravel app—formatting data, generating slugs, or handling common logic. Custom helper functions are perfect for this.
Here’s the simplest way to create them in Laravel.
Step 1: Create a Helper File
Create a new file:
app/Helpers/helpers.php
Add your helper functions:
<?php
if (!function_exists('format_price')) {
function format_price($amount)
{
return '₹' . number_format($amount, 2);
}
}
Step 2: Autoload the Helper File
Open composer.json and add the file under autoload → files:
"autoload": {
"files": [
"app/Helpers/helpers.php"
]
}
Then run:
composer dump-autoload
Step 3: Use the Helper Anywhere
Now you can call your helper function from anywhere in your app:
echo format_price(1500);
Output:
₹1,500.00
Optional: Organize Multiple Helpers
You can create multiple helper files like:
app/Helpers/string.php
app/Helpers/date.php
app/Helpers/common.php
And list them all in composer.json.
Top comments (0)