This post will teach you how to write and utilise custom Laravel helper functions..
Step 1: Make a helper file.
Create a new helper file in the app/Helpers directory to get started. Make the directory if it doesn't already exist.
mkdir app/Helpers
Make a new PHP file now, like helpers.php:
touch app/Helpers/helpers.php
Step 2: Create your own helper functions
After creating the helpers.php file, open it and create your functions. For instance:
<?php
if (!function_exists('format_price')) {
function format_price($amount, $currency = '₹') {
return $currency . number_format($amount, 2);
}
}
if (!function_exists('generate_slug')) {
function generate_slug($string) {
return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string), '-'));
}
}
Step 3: Open composer.json and load the helper file.
You must load the helper file using Composer's autoload functionality in order for Laravel to recognise it. In the autoload
section of your composer.json
file, add the following:
"autoload": {
"files": [
"app/Helpers/helpers.php"
]
}
After adding the helper file, run the following command to update Composer’s autoload files:
composer dump-autoload
Step 4: Use Your Custom Helper Functions
Now you can use your helper functions anywhere in your Laravel application:
$price = format_price(1234.56); // Output: ₹1,234.56
$slug = generate_slug("Hello World!"); // Output: hello-world
Top comments (0)