Laravel 9 custom helper with functions; In this tutorial, you will learn how to create and use a custom helper in laravel 9 apps. And how to call the helper function in laravel 9 on blade view, controller, and model files.
Note that, Laravel 9 custom helper helps to reduce the re-writing the same code again and again. In this custom helper tutorial, we will show an example of how we can create a function in custom helper and how to call this function.
How To Create & Use Custom Helper Function In Laravel 9
Use the following steps to create and use custom helper functions in laravel 9 apps:
- 1 – Create helpers.php File
- 2 – Add File Path In composer.json File
- 3 – Run Command for autoloading
1 – Create helpers.php File
In this step, we need create helpers.php in the laravel project inside the app directory.
In this file, we can write our own custom functions and call anywhere in laravel blade view, controller and model file.
For example, we can create a following functions in custom helpers.php file:
<?php function random_code(){ return rand(1111, 9999); } function allUpper($str){ return strtoupper($str); }
2. Add File Path In composer.json File
In this second step, we will add the path of the helpers file in the composer.json file. Let’s go to project root directory and open composer.json file and update the below-given code into the file:
composer.json
"autoload": { "psr-4": { "App\\": "app/", "Database\\Factories\\": "database/factories/", "Database\\Seeders\\": "database/seeders/" }, "files": [ "app/helpers.php" ] },
3 – Run Command for autoloading
In this final step, go to the command prompt and type the given command:
composer dump-autoload
After run the above command on command prompt. Then we can use custom helper functions by calling this functions name.
How to use helper function in laravel
Now, we will learn how to call or use above created custom helper function in laravel by examples:
1 – How to call helper function in laravel blade
We can see the following example of how to call helper function in laravel blade view file:
<h2><?php echo allUpper('I am from tutsmake.com') ?></h2>
2 – How to call helper function in laravel controller
We can see the following example of how to call helper function in laravel controller file:
public function index() { $data['title'] = allUpper('Title'); return view('view', $data); }
Conclusion
In this tutorial, you have learned how to create helper and functions in laravel And as well as how to use/call helper functions in laravel on blade view, controller file.