Question
How to Create Custom Helper Functions in Laravel
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:
- Create a PHP file for helper functions
- Define normal PHP functions inside it
- Autoload that file through Composer
- 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.
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:
{
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:
- Laravel starts and Composer autoloads
app/helpers.php. - PHP reads the function definition for
fooFormatText(). - The Blade view calls
fooFormatText(' hELLo woRLD '). - The function receives the string
' hELLo woRLD '. - It checks whether the value is or an empty string.
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
- showing fallback text like
-
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() !== ? () : ;
}
}
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( ):
{
? : ;
}
}
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);
}
Comparisons
| Approach | Best for | Pros | Cons |
|---|---|---|---|
| Global helper function | Small reusable logic used in many places | Simple, fast to call, works in Blade easily | Global namespace can get crowded |
| Blade inline logic | Very tiny one-off output logic | Quick for trivial cases | Becomes messy and repetitive fast |
| Blade directive | Reusable Blade-specific syntax | Clean templates for repeated view patterns | More setup than a helper |
| Service class | Larger or business-focused logic | Organized, testable, dependency-friendly | More boilerplate for small tasks |
| Static utility method | Grouped reusable logic | Better organization than many globals | Slightly more verbose to call |
Helper vs service class
Use a when:
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) }}
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.
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.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.