Question

How to Create Custom Helper Functions in Laravel

phplaravellaravel-8laravel-bladelaravel-helper

Question

I want to create reusable helper functions in Laravel so I do not repeat the same logic across multiple Blade views. For example, in a view I would like to call a custom text-formatting function like this:

<p>Foo formatted text: {{ fooFormatText($text) }}</p>

These functions would mainly handle text formatting and similar small pieces of reusable logic. What is the correct way to define globally available helper functions such as fooFormatText() in Laravel?

Short Answer

By the end of this page, you will understand what Laravel helper functions are, how to create your own global helpers, how to load them correctly with Composer, and when using a helper is better than putting logic directly in a Blade view.

Concept

In Laravel, a helper function is a plain PHP function that you can call from many places in your application, including:

  • Blade views
  • Controllers
  • Services
  • Jobs
  • Middleware

Custom helpers are useful when you have small reusable logic that does not belong to a full class. A common example is text formatting, value normalization, URL formatting, or display helpers.

A helper like fooFormatText() lets you move repeated logic out of your templates. That keeps your Blade files cleaner and easier to read.

For example, instead of repeating formatting code in many views, you can centralize it:

<p>{{ fooFormatText($text) }}</p>

This matters because real projects often grow quickly. If formatting logic is copied into many places:

  • bugs are harder to fix
  • updates must be made in multiple files
  • views become harder to maintain

In Laravel, the usual way to make a custom helper globally available is:

  1. Create a PHP file for helper functions
  2. Define normal PHP functions inside it
  3. Autoload that file through Composer
  4. Run composer dump-autoload

This makes the functions available throughout the application.

A helper is best for small stateless reusable functions. If the logic becomes large, depends on services, or needs testing through dependency injection, a class-based solution is often better.

Mental Model

Think of a helper function like a shared utility tool in a workshop.

If every room in the workshop needs a screwdriver, you do not build a new one in each room. You keep one common tool in a known place and use it wherever needed.

A Laravel helper works the same way:

  • your Blade view is the room
  • the repeated formatting logic is the screwdriver
  • the helper file is the shared toolbox

Instead of repeating the same code in every view, you place it in one reusable function and call it anywhere.

Take Quiz

Syntax and Examples

A common approach in Laravel is to create a helper file such as app/helpers.php.

Example helper file

<?php

if (! function_exists('fooFormatText')) {
    function fooFormatText(?string $text): string
    {
        if ($text === null || $text === '') {
            return '';
        }

        return ucwords(strtolower(trim($text)));
    }
}

Why use function_exists?

It prevents PHP from throwing an error if the function is accidentally loaded more than once.

Load the helper with Composer

In your composer.json, add the file under autoload.files:

{
  "autoload": {
    "files": [
      "app/helpers.php"
    ]
  }
}

Then run:

composer dump-autoload

Use it in a Blade view

<p>Foo formatted text: {{ fooFormatText($text) }}</p>

Another example

<?php

if (! function_exists('excerpt')) {
    function excerpt(?string $text, int $length = 50): string
    {
        $text = trim((string) $text);

        if (strlen($text) <= $length) {
            return $text;
        }

        return substr($text, 0, $length) . '...';
    }
}

Usage:

<p>{{ excerpt($post->body, 100) }}</p>

This keeps Blade simple while reusing formatting logic cleanly.

Step by Step Execution

Consider this helper:

<?php

if (! function_exists('fooFormatText')) {
    function fooFormatText(?string $text): string
    {
        if ($text === null || $text === '') {
            return '';
        }

        return ucwords(strtolower(trim($text)));
    }
}

And this Blade usage:

{{ fooFormatText('  hELLo woRLD  ') }}

Here is what happens step by step:

  1. Laravel starts and Composer autoloads app/helpers.php.
  2. PHP reads the function definition for fooFormatText().
  3. The Blade view calls fooFormatText(' hELLo woRLD ').
  4. The function receives the string ' hELLo woRLD '.
  5. It checks whether the value is null or an empty string.
    • It is not, so execution continues.
  6. trim($text) removes spaces from the beginning and end.
    • Result: 'hELLo woRLD'
  7. strtolower(...) converts all letters to lowercase.
    • Result: 'hello world'
  8. ucwords(...) capitalizes the first letter of each word.
    • Result: 'Hello World'
  9. The function returns 'Hello World'.
  10. Blade outputs the returned value.

Final rendered output:

Hello World

This shows why helpers are useful: the view stays short, and the logic is handled in one reusable place.

Real World Use Cases

Custom helpers are commonly used for small repeated tasks such as:

  • Formatting display text

    • title casing names
    • trimming extra spaces
    • generating excerpts
  • Formatting values for views

    • currency display
    • date display wrappers
    • status labels
  • Normalizing input

    • removing extra whitespace
    • cleaning phone numbers
    • standardizing codes
  • Presentation helpers in Blade

    • showing fallback text like N/A
    • shortening long strings
    • converting booleans to readable labels
  • Small utility logic used across the app

    • environment display helpers
    • asset or path convenience helpers
    • string transformation helpers

Example:

if (! function_exists('displayName')) {
    function displayName(?string $name): string
    {
        return $name && trim($name) !== '' ? trim($name) : 'Anonymous';
    }
}

Used in Blade:

<p>{{ displayName($user->name) }}</p>

This is the kind of small reusable logic helpers are good at.

Take Quiz

Real Codebase Usage

In real Laravel codebases, developers usually use helpers for simple reusable functions and avoid putting too much business logic into them.

Common patterns include:

Guard clauses

Helpers often return early for invalid or empty input.

if (! function_exists('safeUpper')) {
    function safeUpper(?string $value): string
    {
        if ($value === null || trim($value) === '') {
            return '';
        }

        return strtoupper(trim($value));
    }
}

This makes the function easier to read.

View-focused formatting

Helpers are often used for logic that improves display, not core business rules.

if (! function_exists('statusLabel')) {
    function statusLabel(bool $active): string
    {
        return $active ? 'Active' : 'Inactive';
    }
}

Validation-friendly defaults

Helpers can safely handle missing values to avoid noisy checks in views.

if (! function_exists('fallback')) {
    function fallback($value, string $default = 'N/A'): string
    {
        return filled($value) ? (string) $value : $default;
    }
}

Keeping Blade clean

Instead of this in Blade:

{{ $text ? ucwords(strtolower(trim($text))) : '' }}

developers prefer:

{{ fooFormatText($text) }}

When teams avoid helpers

Large teams may avoid too many global functions because:

  • names can collide
  • global helpers can become hard to organize
  • class methods are easier to group and test in structured ways

In those cases, developers may use:

  • view composers
  • Blade directives
  • service classes
  • value objects
  • presenter classes

So helpers are common, but best kept small and focused.

Common Mistakes

1. Forgetting to autoload the helper file

Creating app/helpers.php is not enough by itself. If Composer does not load it, Laravel will not know the function exists.

Broken setup

<?php

function fooFormatText($text)
{
    return trim($text);
}

If this file is never autoloaded, calling the function causes an error like:

Call to undefined function fooFormatText()

Fix

Add it to composer.json and run:

composer dump-autoload

2. Defining the same function twice

If two files define the same global function, PHP throws a fatal error.

Broken code

function fooFormatText($text)
{
    return trim($text);
}

Better

if (! function_exists('fooFormatText')) {
    function fooFormatText($text)
    {
        return trim($text);
    }
}

3. Putting too much logic in helpers

Helpers should stay small. Do not put large business workflows into a global function.

Not ideal

function processOrder($order)
{
    // validation
    // pricing rules
    // payment logic
    // email sending
    // logging
}

This belongs in services or classes, not a helper.

4. Writing logic directly in Blade instead of using a helper

Hard to read

{{ $text !== null && trim($text) !== '' ? ucwords(strtolower(trim($text))) : '' }}

Better

{{ fooFormatText($text) }}

5. Not handling null or empty values

Risky

function fooFormatText($text)
{
    return ucwords(strtolower(trim($text)));
}

If null is passed, this may behave unexpectedly depending on PHP version and strictness.

Better

function fooFormatText(?string $text): string
{
    if ($text === null || $text === '') {
        return '';
    }

    return ucwords(strtolower(trim($text)));
}

6. Choosing unclear helper names

A name like formatText() may be too generic in a large app.

Use names that describe purpose clearly, such as:

  • fooFormatText()
  • displayName()
  • statusLabel()
  • excerpt()

Comparisons

ApproachBest forProsCons
Global helper functionSmall reusable logic used in many placesSimple, fast to call, works in Blade easilyGlobal namespace can get crowded
Blade inline logicVery tiny one-off output logicQuick for trivial casesBecomes messy and repetitive fast
Blade directiveReusable Blade-specific syntaxClean templates for repeated view patternsMore setup than a helper
Service classLarger or business-focused logicOrganized, testable, dependency-friendlyMore boilerplate for small tasks
Static utility methodGrouped reusable logicBetter organization than many globalsSlightly more verbose to call

Helper vs service class

Use a helper when:

  • logic is small
  • logic is stateless
  • it is mostly formatting or simple transformation
  • you want easy usage in Blade

Use a service class when:

  • logic is complex
  • logic depends on other services
  • you need dependency injection
  • the code represents business rules

Helper vs Blade directive

A helper returns a value:

{{ fooFormatText($text) }}

A Blade directive changes template syntax and is better when you want custom templating behavior.

For simple formatting, a helper is usually easier.

Take Quiz

Cheat Sheet

// app/helpers.php
<?php

if (! function_exists('fooFormatText')) {
    function fooFormatText(?string $text): string
    {
        if ($text === null || $text === '') {
            return '';
        }

        return ucwords(strtolower(trim($text)));
    }
}
// composer.json
{
  "autoload": {
    "files": [
      "app/helpers.php"
    ]
  }
}
composer dump-autoload
{{ fooFormatText($text) }}

Quick rules

  • Put small reusable functions in a helper file
  • Load the file with Composer autoload
  • Run composer dump-autoload after changes to autoload config
  • Wrap functions with if (! function_exists(...))
  • Keep helpers small and focused
  • Prefer helpers for formatting and simple transformations
  • Use classes for complex business logic

Good helper characteristics

  • short
  • reusable
  • stateless
  • easy to name clearly
  • safe with null or empty input

Common error

Call to undefined function ...

Usually means:

  • helper file is not autoloaded
  • autoload was not refreshed
  • function name is misspelled

FAQ

How do I make a custom Laravel helper globally available?

Create a PHP file such as app/helpers.php, add your functions there, register the file in composer.json under autoload.files, and run composer dump-autoload.

Can I use custom helper functions inside Blade views?

Yes. Once the helper file is autoloaded, you can call the function directly in Blade, such as {{ fooFormatText($text) }}.

Where should Laravel helper functions be stored?

A common simple choice is app/helpers.php. Some projects use a app/Support/helpers.php file or multiple helper files for better organization.

Should I use helpers or service classes in Laravel?

Use helpers for small stateless reusable logic. Use service classes when logic is larger, business-related, or depends on other services.

Why do I get "Call to undefined function" for my helper?

Usually because the helper file was not autoloaded, the Composer autoload cache was not refreshed, or the function name does not match.

Can I create multiple helper files in Laravel?

Yes. You can list multiple files in composer.json under autoload.files.

Is it bad practice to use global helper functions in Laravel?

Not for small focused utilities. It becomes a problem when too many helpers are added or when they contain complex business logic.

Do I need function_exists() around helper functions?

It is strongly recommended. It helps prevent fatal errors if the same function is loaded more than once.

Take Quiz

Mini Project

Description

Create a small text formatting helper set for a Laravel application. The goal is to move repeated display logic out of Blade templates and into reusable global helper functions. This mirrors real projects where user names, excerpts, and fallback text are displayed in many views.

Goal

Build and use globally available Laravel helper functions for text formatting in Blade views.

Requirements

Create a helper file that contains at least two custom functions. Register the helper file with Composer so the functions are globally available. Use one helper to format text and another to provide fallback display text. Call both helpers from a Blade view. Make sure the helpers safely handle null or empty input.

Take Quiz

Keep learning

Related questions

View more