In this tutorial you will learn about the How to Create Custom Helper In Laravel and its application with practical example.
In this How to Create Custom Helper In Laravel tutorial I will show you how to create custom helper in laravel. In this tutorial you will learn to create custom helper file in laravel. With custom helper file you can define functions that you can reuse in your laravel application.
What Laravel Custom Helper
In laravel, 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 project.
How to Create Custom Helper In Laravel
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 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?php function imploadValue($types){ $strTypes = implode(",", $types); return $strTypes; } function explodeValue($types){ $strTypes = explode(",", $types); return $strTypes; } function random_code(){ return rand(1111, 9999); } function remove_special_char($text) { $t = $text; $specChars = array( ' ' => '-', '!' => '', '"' => '', '#' => '', '$' => '', '%' => '', '&' => '', '\'' => '', '(' => '', ')' => '', '*' => '', '+' => '', ',' => '', '₹' => '', '.' => '', '/-' => '', ':' => '', ';' => '', '<' => '', '=' => '', '>' => '', '?' => '', '@' => '', '[' => '', '\\' => '', ']' => '', '^' => '', '_' => '', '`' => '', '{' => '', '|' => '', '}' => '', '~' => '', '-----' => '-', '----' => '-', '---' => '-', '/' => '', '--' => '-', '/_' => '-', ); foreach ($specChars as $k => $v) { $t = str_replace($k, $v, $t); } return $t; } |
Add File Path In composer.json File
In this step, we will add 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 13 14 15 16 17 18 19 20 21 |
"autoload": { "classmap": [ ... ], "psr-4": { "App\\": "app/" }, "files": [ "app/helpers.php" ] }, |
Now, go to command prompt and type the given command:
1 |
composer dump-autoload |
Now you can use your custom helper functions by calling this functions remove_special_char(), random_code() etc.
Now, I’ll show you how to use custom helper function in your laravel project:
Example 1
1 2 |
$code = random_code(); print_r($code); |
Example 2
1 2 3 4 5 6 7 |
$str = "remove & special #character *in string@$ example." $remove = remove_special_char($str); print_r($remove); //output remove special character in string example |