How to Create a Public Helper Function in Laravel

Public helper is useful for functions that are repeatedly used by a lot of components, controllers, actions, etc. Implementing a public helper function can speed up your development process as it already exists in your application, developers can just call it and use it right away. Also, it helps keep the core function in one place and reduces the redundancy of the code, whether it has an error or you need to modify it sometimes, you can just update it in one place. Follow the steps in this article to create your public helper function.

Create Helper.php class

In the ./app/Supports/Helpers/helper.php

<?php

/**
 * Test helper
*/
if (!function_exists('testHelper')) {
    function testHelper() {
        return 'true';
    }
}

Create HelperServiceProvider

Running the below command in the terminal to create a HelperServiceProvider that will be used later to inject into the Laravel app provider.

php artisan make:provider HelperServiceProvider

After that register all your helper PHP functions in the provider (register method). 

In the ./app/Providers/HelperServiceProvider.php

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

class HelperServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $dir = base_path('app/Supports/Helpers');
        $scans = glob("$dir/*.php");
        foreach ($scans as $scan) {
            if(is_file($scan)) {
                require_once($scan);
            }
        }
    }

    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

Integrate service provider to the application

Now add your HelperServiceProvider to config/app.php in the providers array. This will inject the provider to the Laravel application on the register method it will then require every function in the Helper.php and you will have access to all the helper functions globally.

In the ./config/app.php

<?php

return [

    'name' => env('APP_NAME', 'Laravel'),

    'env' => env('APP_ENV', 'production'),

    'debug' => (bool) env('APP_DEBUG', false),

    'url' => env('APP_URL', 'http://localhost'),

    'asset_url' => env('ASSET_URL', null),

    'timezone' => 'UTC',

    'locale' => 'en',

    'fallback_locale' => 'en',

    'faker_locale' => 'en_US',

    'key' => env('APP_KEY'),

    'cipher' => 'AES-256-CBC',

    'providers' => [
        /*
         * Laravel Framework Service Providers...
         */
        Illuminate\Auth\AuthServiceProvider::class,
        Illuminate\Broadcasting\BroadcastServiceProvider::class,
        Illuminate\Bus\BusServiceProvider::class,
        Illuminate\Cache\CacheServiceProvider::class,
        Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class,
        Illuminate\Cookie\CookieServiceProvider::class,
        Illuminate\Database\DatabaseServiceProvider::class,
        Illuminate\Encryption\EncryptionServiceProvider::class,
        Illuminate\Filesystem\FilesystemServiceProvider::class,
        Illuminate\Foundation\Providers\FoundationServiceProvider::class,
        Illuminate\Hashing\HashServiceProvider::class,
        Illuminate\Mail\MailServiceProvider::class,
        Illuminate\Notifications\NotificationServiceProvider::class,
        Illuminate\Pagination\PaginationServiceProvider::class,
        Illuminate\Pipeline\PipelineServiceProvider::class,
        Illuminate\Queue\QueueServiceProvider::class,
        Illuminate\Redis\RedisServiceProvider::class,
        Illuminate\Auth\Passwords\PasswordResetServiceProvider::class,
        Illuminate\Session\SessionServiceProvider::class,
        Illuminate\Translation\TranslationServiceProvider::class,
        Illuminate\Validation\ValidationServiceProvider::class,
        Illuminate\View\ViewServiceProvider::class,

        /*
         * Package Service Providers...
         */
        App\Providers\HelperServiceProvider::class, // <-- Register here

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        // App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
    ],
];

Usage

Now you can call the public function helper everywhere without using any class.

<?php

namespace App\Http\Controllers;

class TestController extends Controller
{
    public function testPublicHelper()
    {
        return testHelper();
    }
}