DeveloperJoy Logo DeveloperJoy

Write your own Laravel helpers

April 11, 2024
Write your own Laravel helpers

Laravel offers a wide range of useful helper functions that simplify tasks like manipulating arrays, file paths, strings, and routes, including the popular dd() function.

You can create custom helper functions for your Laravel projects and PHP packages by leveraging Composer for automatic imports.

If you're new to Laravel or PHP, here's a walkthrough on creating and loading your own helper functions seamlessly within Laravel.

Creating a Helpers file in a Laravel App

One common practice is to place helper functions within a Laravel application. You have the flexibility to organize helper files in various locations, such as:

  • app/helpers.php
  • app/Http/helpers.php

In my case, I usually keep them in app/helpers.php within the primary application namespace.

Autoloading

To utilize your PHP helper functions effectively, they need to be loaded dynamically at runtime. Instead of manual inclusion using require or require_once, Composer provides a more efficient solution for autoloading.

When setting up a new Laravel project, the composer.json file contains autoload and autoload-dev keys. You can specify your helpers file under the files key within autoload, enabling automatic loading:

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

Remember to run composer dump-autoload after modifying the autoload configuration to ensure the autoloader picks up the changes.

Defining Functions

When defining functions in your helpers class, ensure to prevent function definition conflicts by wrapping them in function_exists checks. This guards against unexpected clashes in function definitions due to the order of inclusion.

By adhering to naming conventions and potentially prefixing function names, you can reduce the likelihood of collisions and enhance the clarity of your codebase.

For example, in Monse, one of my clients, we have some helpers to format numbers and they are defined like this:

if (! function_exists('format_currency') {
  function format_currency(int $amount, string $currency): string
  {
      $locale = match ($currency) {
          'EUR' => 'es_ES',
          // ...
          default => 'en_US',
      };

      return (new NumberFormatter($locale, NumberFormatter::CURRENCY))
          ->formatCurrency($amount / 100, $currency);
  }
}

Then you can directly use this function everywhere in your project because it's already preloaded with composer.

Packages

When developing Composer packages, consider including a helpers file to provide essential functions to projects using your package. Make sure to use function_exists() checks to prevent conflicts and choose unique function names to prevent clashes.


Check Composer's autoloading documentation for more insights on file inclusion and autoloading classes effectively.

← Go back to the blog

Work with me

Do you own a company or need help with your Laravel project? I can help you with that. Check the plans and let me know if you have any questions.

Get 1 month free with yearly plan during checkout.

Technical Advisor

$ 3 ,995

/m

What's included:

  • Lead your team to a better code architecture, testing mentality, clean code, and more.
  • Lead knowledge-sharing sessions depending on current company status and requirements.
  • Help with product and technical decisions.
  • Pause or cancel anytime.

Integrated Senior Developer

$ 5 ,995

/m

What's included:

  • Includes all Technical Advisor services.
  • Engages as a team member in daily tasks.
  • Participates actively in day-to-day development.
  • Direct communication:
    Slack, and meetings included.
  • Pause or cancel anytime.

Want to talk first?

Ok, just book a call now.

FAQ