DEV Community

Cover image for Creating Own PHP Helpers in a Laravel Project
Chetan Rohilla
Chetan Rohilla

Posted on • Updated on • Originally published at w3courses.org

Creating Own PHP Helpers in a Laravel Project

Laravel has variety of global “helper” functions. We are free to use them in our own applications like app_path, ucfirst, auth, env etc. We can also define our own set of helper functions for Laravel applications and PHP packages. And we can use composer to import them. Also we can use them directly without import.

Creating a Helpers file in a Laravel App

First create a file in app/Helpers/Helper.php

Autoloading Helper File in Laravel

Open composer.json file and add file path in files key as shown below.

"autoload": {
    "files": [
        "app/Helpers/Helper.php"
    ],
    "classmap": [
        "database/seeds",
        "database/factories"
    ],
    "psr-4": {
        "App\\": "app/"
    }
},
Enter fullscreen mode Exit fullscreen mode

Once you add a new path to the files array, you need to dump the autoloader:

composer dump-autoload
Enter fullscreen mode Exit fullscreen mode

Defining Helper Functions in Laravel

Now, you can create your own helper functions as shown below.

if (! function_exists('myCustomFunc')) {
    function myCustomFunc($default = null) {
        // ...
    }
}
Enter fullscreen mode Exit fullscreen mode

If you are unable to run composer commands. Then you should try this method.

Open your helper file app/Helpers/Helper.php. Create a class And create static functions as shown below.

<?php

namespace App\Helpers;

class Helper
{

    public static function myCustomFunc()
    {

    }

}
Enter fullscreen mode Exit fullscreen mode

Now, Creating Own PHP Helpers in a Laravel Project and use functions like this \App\Helpers\Helper::myCustomFunc().


Please like share subscribe and give positive feedback to motivate me to write more for you.

For more tutorials please visit my website.

Thanks:)
Happy Coding:)

Top comments (0)