Laravel 12 Create Custom Helper Function

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

Steps to Create a Custom Helper Function in Laravel 12

 

Step 1: Install Laravel 12

Install laravel 12 using the following command.

laravel new example-app

 

Step 2: Create a helpers.php File

In the app/Helpers/helpers.php create a new file.

if (!function_exists('greetUser')) {
    function greetUser($name)
    {
        return "Hello, " . ucfirst($name) . "!";
    }
}

 

Step 3: Load the Helper in composer.json

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"
        ]
    },
  
...

 

Step 4: Dump Autoload Files

Run the following command to refresh Composer's autoload files:

composer dump-autoload

 

Step 5: Use Your Helper Function

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:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS