How to create a custom helper file and function in Laravel?

In this post we will learn how to create your own custom helper file so you can write your own custom helper function in laravel.

Create a folder : First, create a folder named Helpers in your laravel project inside the app directory. In this folder, you need to create a file named utilities.php

After creating utilities.php, We need to add file path to composer.json file

"autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        },
        "files": [
            "app/Helpers/utilities.php"
        ]
    },

Now we need run autoload command to regenerate composer's autoloader so laravel can find your helper file which is utilities.php

composer dump-autoload

After composer autoload, You can start creating your own custom function in utilities.php

<?php
if (!function_exists('categories'))
{
    function categories()
    {
        $data = ['php' => 'PHP', 'laravel' => 'Laravel', ];

        return $data;
    }
}

The ' if (!function_exists()) ' statement in PHP is used to check if a function has been defined before attempting to use it. This is particularly useful in cases where you want to avoid errors that would occur if you tried to redefine a function that already exists.


Now you can directly call categories function anywhere in any file.

$categories = categories();
foreach($categories as $category)
{
    echo $category;
}