Reader Stacks

Custom Helper Functions in Laravel 11 and 12

How to register global helper functions in Laravel 11 and 12, including the composer.json autoload change from older versions.

Custom Helper Functions in Laravel 11 and 12

Laravel doesn't ship a dedicated helpers file, but adding your own global functions — a currency formatter, a slug generator, a shortcut you call in dozens of Blade views — is a common and supported pattern. The setup is the same in Laravel 11 and 12; only the surrounding app-structure files have changed from older tutorials, so version mismatches are the most common source of confusion here.

1. Create the helpers file

Create app/helpers.php (some projects use app/Support/helpers.php — either works, as long as the path below matches):

<?php

if (! function_exists('money')) {
    function money(int $cents, string $currency = 'USD'): string
    {
        return number_format($cents / 100, 2).' '.$currency;
    }
}

The function_exists guard matters more than it looks: without it, running the same helper file twice in a test suite or a package that also defines money() throws a fatal "cannot redeclare function" error.

2. Autoload it via composer.json

Add the file to the autoload.files array in composer.json:

"autoload": {
    "files": [
        "app/helpers.php"
    ],
    "psr-4": {
        "App\\": "app/"
    }
}

Then regenerate the autoloader:

composer dump-autoload

What changed from Laravel 8/9 tutorials

Older guides sometimes have you load the helper file from AppServiceProvider::register() with a manual require. That still works, but it's unnecessary — the Composer autoload.files approach is simpler, doesn't run on every service provider boot, and is what Laravel's own first-party packages use internally.

Using it

Once autoloaded, money() is available anywhere — controllers, Blade templates, Artisan commands, without an import:

{{ money($order->total_cents) }}

Common mistake

If the function isn't found after adding it, the fix is almost always composer dump-autoload — Composer only scans autoload.files entries when the autoloader is regenerated, not on every request in production (though in local development with APP_DEBUG enabled and Composer's file watcher, it often picks it up automatically).

Topics: Developer Productivity