Through Laravel 9 custom helper functions example tutorial, we will learn how to create and use a custom helper in laravel 9 app. Using this tutorial we also lean how to call the helper function in laravel blade view, controller, and model files.
You can use this cutom helper global function example in laravel 5, laravel 6, laravel 7, laravel 8 or laravel 9 version.
Laravel 9 Custom Global Helper Functions Example
Use the following steps to create and use custom helper functions in laravel 9 apps:
- Step 1: Create helpers.php File
- Step 2: Add File Path in composer.json File
- Step 3: Run auto-dump Command
- Step 4: How to Use Helper Function
Step 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 generateRandomCode(){
return rand(1111, 9999);
}
function convertUpperCase($str){
return strtoupper($str);
}
Step 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:
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files": [
"app/helpers.php"
]
},
Step 3: Run dump-autoload Command
this is the last step, you should just run following command
composer dump-autoload
After run the above command on command prompt. Then we can use custom helper functions by calling this functions name.
Step 4: How to use helper function in laravel
Now, we will learn how to call or use above created custom helper function in laravel 8 by examples:
Use 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 convertUpperCase('This is test title with helper function') ?></h2>
Use 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['random_code'] = generateRandomCode();
return view('view', $data);
}
In this tutorial, we have learned how to create helper and functions in laravel 9. And as well as how to use/call helper functions in laravel 8 on blade view, controller file.