In this laravel tutorial titled “laravel 12 create custom helper function” I will show you how to create custom helper function step by step with example.
Laravel helper functions are globally accessible PHP methods that offer simplified solutions for performing common tasks across your application. These functions help reduce repetitive code and make your code more readable and expressive. You can call these functions from anywhere—controllers, views, middleware, service providers etc —without importing any class.
You can also define custom helper functions for your Laravel application. To make them available globally, add the helper file in composer.json so it loads automatically.
Laravel offers a wide range of helper functions for various purposes, such as:
- String Manipulation
- Array Operations
- URL Generation
- Debugging
Laravel provides many built-in helper functions. Here are a few popular ones:
- url()-Generate a full URL for a given path
- route()-Get the URL for a named route
- asset()-Generate a URL for a public asset (e.g., CSS/JS)
- config()-Retrieve values from configuration files
- dd()-Dump and die (useful for debugging)
Steps for Laravel 12 Create Custom Helper Function
- Step 1: Install Laravel 12
- Step 2: Create a helpers File
- Step 3: Autoloading helper.php via composer.json
- Step 4: Dump Autoload Files
- Step 5: Use Your Helper Function
Let’s get started.
Step 1: Install Laravel 12
To get started, you’ll need a Laravel project. If you already have one set up, you can skip this step. Otherwise, run the following command in your terminal to create a new Laravel application:
composer create-project laravel/laravel laravel-custom-helper-demo
Once the project installation is complete, you can proceed to the next step.
Step 2: Create a helpers File
In this step, we will create a helper file named helpers.php inside the app/Http folder. However, you can place the helpers.php file in any location based on your preference.
app/Http/helpers.php
<?php
use Carbon\Carbon;
if(!function_exists('formatDate')){
function formatDate($date)
{
return Carbon::parse($date)->format('Y M d');
}
}
if(!function_exists('formatText')){
function formatText($text)
{
return strtoupper($text);
}
}
Laravel wraps all its helper functions in a check to prevent errors from defining the same function more than once. I always prefer to use function_exists checks when writing helper functions in my Laravel apps. Without it, PHP will throw an error if the same function is defined more than once — which can help catch issues early. While name collisions are rare, it’s still a good idea to avoid using very generic names. To reduce the risk of conflicts, you can also prefix your function names.
Step 3: Autoloading helper.php via composer.json
In this step, we will register our helpers.php file in the composer.json file. When you open composer.json file, you will see two main sections: autoload and autoload-dev. We need to define a files key inside the autoload ,To load the helpers.php file automatically. This files key is an array where you can list file paths that should be included automatically by Composer.
............................................................
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files":[
"app/Http/helpers.php"
]
},
............................................................
Step 4: Dump Autoload Files
Run the following command to update the Composer autoloader, so that the helpers.php file is loaded automatically:
composer dump-autoload
Read Also : Laravel 12 Custom Login with Remember Me Feature
Step 5: Use Your Helper Function
After successfully running composer dump-autoload, we can now use our custom helper functions. These functions can be called from anywhere in your Laravel application—such as controllers, routes, views, and more. For example, you can use them in a controller or route like this:
echo formatDate(now()); //2025 Jul 18
echo formatText("hello"); //HELLO
The output is:
2025 Jul 18
HELLO
Use in blade File:
You can also call the helper function inside a Blade view like this:
<h1>{{formatDate(now())}}</h1> <!--2025 Jul 18 -->
<h2>{{formatText("hello")}} User </h2> <!--HELLO-->
The output is:

Conclusion
Creating custom helper functions in Laravel 12 is a simple, scalable way to centralize repeatable logic and make code more expressive across controllers, routes, views, and more. By adding a helpers.php file, registering it under the files array in composer.json, and running composer dump-autoload, these utilities become globally available without additional imports. Following best practices—such as wrapping functions with function_exists checks, choosing clear and unique names to avoid collisions, and organizing helpers under app/Helpers for larger projects—keeps the codebase maintainable and safe. For advanced control, helpers can be conditionally loaded per environment through a service provider, while still retaining the convenience of global access. With thoughtful structure and naming, custom helpers offer a lightweight alternative to helper classes or traits for formatting, parsing, and other common tasks, improving both development speed and readability.
Frequently Asked Questions(FAQs)
Q1: What is a custom helper function in Laravel 12?
A custom helper function is a globally accessible PHP function you define to reuse common logic across controllers, views, routes, and other parts of your Laravel application.
Q2: Why should I use custom helper functions?
You should use custom helper functions in Laravel when you have repetitive tasks or logic that needs to be accessed across multiple parts of your application.
Q3: Where should I create my helpers.php file?
You can create your helpers.php file anywhere in your Laravel project, but the most common and organized locations are
- Inside the app/ directory (e.g., app/helpers.php) – Simple and keeps it close to your main application code.
- Inside a dedicated app/Helpers/ folder (e.g., app/Helpers/helpers.php) – Best for larger projects or when you plan to have multiple helper files.
Q4: How do I define a helper function safely?
Wrap each function in an if (!function_exists(‘your_function_name’)) { … } block to prevent redeclaration errors if the file is loaded more than once.
Q5: Do I need a namespace for helper functions?
No, helper functions in Laravel don’t need a namespace — they’re loaded globally once registered in composer.json
.
Q6: How do I use a helper function in controllers or routes?
After autoloading, call it directly by name, e.g., formatDate(now()); in controllers, routes, jobs, or middleware.
Q7: Do I have to run composer dump-autoload every time I change helpers.php?
No — you only need to run composer dump-autoload
after creating or renaming helpers.php
.
For edits to existing functions, Laravel will load the changes automatically.
Q8: What if composer dump-autoload doesn’t pick up my helpers?
If composer dump-autoload doesn’t load your helpers, check that:
- Ensure the helpers.php path is correct in composer.json
- clear caches (php artisan optimize:clear), and verify that the file exists and is readable by the application.
Q9: Are there naming conflicts with Laravel’s built-in helpers?
Yes — if your helper function name matches a Laravel built-in helper, it will cause a conflict or override it.
To avoid this, use unique, descriptive names (e.g., appFormatDate() instead of formatDate()).
Q10: What is the difference between a trait and a helper function in Laravel?
Trait : A trait is a reusable block of methods mixed into classes, useful when shared behavior needs access to the object context via $this and class properties, effectively working around PHP’s lack of multiple inheritance.
Helper Function : A helper function is a global, stateless utility function callable anywhere, ideal for simple tasks like formatting, parsing, or quick calculations.
Q11: Is it possible to conditionally load helpers only in certain environments?
Yes — you can load helpers conditionally by requiring them in a service provider with an environment check:
/**
* Register any application services.
*/
public function register(): void
{
if ($this->app->environment('local')) {
require_once app_path('Helpers/local_helpers.php');
} elseif ($this->app->environment('production')) {
require_once app_path('Helpers/production_helpers.php');
}
}
This ensures they’re only loaded in environments like local
, staging
, or any you specify.
Q12: Are helper classes better than global functions?
It depends on your needs:
- Helper Classes : Better for organization, namespacing, testability, and avoiding naming conflicts.
- Global Functions : Quicker to use, no need for instantiation, but risk of conflicts and harder to autoload selectively.
Q12: Will helpers increase my app’s load time?
No — helpers have a negligible impact on load time because they’re loaded once and cached by Laravel’s autoloader. Performance issues only arise if helpers contain heavy logic that runs on every request.
Q13: What are common mistakes when creating helpers?
Common mistakes include forgetting to add the file to composer.json, not running composer dump-autoload after changes to autoload config, naming conflicts with built-in helpers, and missing function_exists guards.
Q14: Is there an alternative to autoload “files” for loading helpers?
Yes, you can include the helpers file from a custom service provider’s boot method, but using composer’s files autoload is simpler for most cases.
public function boot()
{
require_once app_path('Helpers/helpers.php');
}
This gives you more control, such as conditional loading based on environment.