Hey there! If you're working with Laravel 12 and need reusable functions across your project, creating a custom helper function is the way to go. It saves time and keeps your code clean. In this guide, I'll show you how to set up a helper function in Laravel 12 step by step.
Steps to Create a Custom Helper Function in Laravel 12
Install laravel 12 using the following command.
laravel new example-app
In the app/Helpers/helpers.php create a new file.
if (!function_exists('greetUser')) {
function greetUser($name)
{
return "Hello, " . ucfirst($name) . "!";
}
}
Now, we need to tell Laravel to load our helpers.php file automatically. Open the composer.json file and find the autoload section. Add the helper file under the files array.
...
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files": [
"app/Helpers/helpers.php"
]
},
...
Run the following command to refresh Composer's autoload files:
composer dump-autoload
Now, you can use your helper function anywhere in your Laravel app, like controllers, views, or even routes.
$name = "john";
echo greetUser($name); // Output: Hello, John!
Using Helpers in Blade Templates
You can also use this function inside a Blade file like this:
<p>{{ greetUser('jane') }}</p>
You might also like: