How to define Custom Laravel Helper Function
If you are curious to define custom helper function in Laravel, this post will guide you the step by step process that how to create your custom helper function in your laravel application. Out of the box, Laravel provides you with many useful and handle helpers such as Str::slug()
or ucfirst()
or lot more. Let’s know about the process.
Table of Contents
Step 1:
You need to define a helper file what I called Helpers.php
. You can name it anything and place anywhere. However, I personally practice to place it in app/Utils/
folder that make more sense to me.
app/Utils/Helpers.php
<?php
if(! function_exists('hello_world')){
function hello_world(){
return "Hello World";
}
}
Here, I added a new function called hello_world()
that just return a simple text. You can write whatever logic you need here.
Step 2
Now we need to register to composer.json
file. In your composer.json
file, find autoload
and register your Helpers.php
file.
"autoload": {
...
...
"files": [
"app/Utils/Helpers.php"
]
}
Step 3
Finally, run the following command-
composer dump-autoload
and restart your application.
Step 4
Now you can call hello_world()
function to anywhere in your application and it will return the Hello World
test.
Let me know if you have any question. Thanks for reading. :)