How to Create and Use Custom Helpers in Laravel 10
Hello Devs,
Here's how we can create and use custom helper functions in Laravel 10. You can also use the same process for laravel other versions like 9,8,7 etc.
We need to follow bellow steps to complete the full process of using laravel custom helpers.
Step - 1. Create Helper File
Step - 2. Write Helper Function
Step - 3. Autoload the Helper File
Step - 4. Regenerate Composer Autoload Files
Step - 5. Use the Helper Function
Step - 1. Create Helper File
We can create single or multiple helpers file according to our needs. For simplicity, we'll create a single helpers.php file. Create a new file called helpers.php in the app directory.
Step - 2. Write Helper Function
Open the helpers.php file and start create your custom functions. Now we will create a formatCurrency() function. You can create multiple functions in a single helpers file.
app/helpers.php
function formatCurrency($amount) {
return '$' . number_format($amount, 2);
}
Step - 3. Autoload the Helper File
For Laravel to recognize and autoload your custom helper functions, we'll need to specify the path in composer.json.
1. Open the composer.json file at the root of your Laravel project.
2. Find the autoload section.
3. Add your helpers.php file path to the files array, like bellow.
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files": [
"app/helpers.php"
]
},
Step - 4. Regenerate Composer Autoload Files
After updating the composer.json file, we need to regenerate the autoload files. Run the following command.
composer dump-autoload
Step - 5. Use the Helper Function
Once we've created our helper functions and updated the autoloader, we can use our custom helper functions anywhere in our Laravel application just like we'd use any other function.
For example, in a blade template we can use like this way
{{ formatCurrency(1234.56) }}
In Controller we can also use like this way
public function showPrice() {
$formattedPrice = formatCurrency(1234.56);
return view('price.show', compact('formattedPrice'));
}
Hope this will help you a lot. Thus we can create and user helpres functions in our laravel applications. Thanks to read the article. Please let us know if you have any query.
You May Also Like Bellow Articles:
Laravel 9 live search data in a table using ajax.
How to send SMS in laravel 9 using Twilio SMS API-Webjourney
Laravel 9 pdf invoice generate and download with barryvdh dompdf
How to create multi language website by laravel 9
Laravel 10 multiple form validation on the same page-WebJourney
Laravel 10 Breeze Authentication - WebJourney
Laravel 10 Ajax jQuery Crud with Pagination and Live Search
Laravel Naming Conventions Accepted by Laravel community
Laravel Shorter and More Readable Syntax - WebJourney