In this tutorial you will learn about the Laravel 9 Create Custom Helper Functions Example and its application with practical example.
In this Laravel 9 Create Custom Helper Functions Example tutorial I will show you how to create custom helper in laravel 9. In this tutorial you will learn to create custom helper file in laravel 9 application . With custom helper file you can define functions that you can reuse in your laravel 9 application.
What Is Laravel 9 Custom Helper
In laravel 9, custom helper file helps you to reduce the re-writing the same code again and again. With custom helper file you can define the custom helper functions that you can use anywhere in your laravel 9 project.
How to Create Custom Helper In Laravel 9
In this step by step tutorial I demonstrate you how to create custom helper file in laravel project. I will also show you how to define custom helper function and to call them in laravel application:
Create helpers.php File
In custom helper file you can define your own functions and call anywhere in your laravel project. Go to App directory and create a new file helpers.php like this app/helpers.php.
1 2 3 4 5 6 7 8 9 10 11 |
<?php function random_code(){ return rand(1111, 9999); } function doUpper($str){ return strtoupper($str); } |
Add custom helper File Path In composer.json File
In this step, we will add custom helper file path in composer.json file. Go to root directory and open composer.json file and put the following code into the file:
composer.json
1 2 3 4 5 6 7 8 9 10 11 12 |
"autoload": { "psr-4": { "App\\": "app/", "Database\\Factories\\": "database/factories/", "Database\\Seeders\\": "database/seeders/" }, "files": [ "app/helpers.php" ] }, |
Run Command for autoloading custom helper file
Now, go to command prompt and type the given command:
1 |
composer dump-autoload |
How to use custom helper function in laravel 9
Now, you will learn how to call or use custom helper function in laravel 9:
1 – How to call custom helper function in laravel blade
1 |
<h2><?php echo doUpper('hello world') ?></h2> |
2 – How to call custom helper function in laravel controller
1 2 3 4 5 |
public function index() { $data['title'] = doUpper('hello world'); return view('view', $data); } |