DEV Community

Ankit Verma
Ankit Verma

Posted on

How to Create Custom Helper Functions in Laravel

This post will teach you how to write and utilise custom Laravel helper functions..

Step 1: Make a helper file.

Create a new helper file in the app/Helpers directory to get started. Make the directory if it doesn't already exist.

mkdir app/Helpers
Enter fullscreen mode Exit fullscreen mode

Make a new PHP file now, like helpers.php:

touch app/Helpers/helpers.php
Enter fullscreen mode Exit fullscreen mode

Step 2: Create your own helper functions

After creating the helpers.php file, open it and create your functions. For instance:

<?php

if (!function_exists('format_price')) {
    function format_price($amount, $currency = '₹') {
        return $currency . number_format($amount, 2);
    }
}

if (!function_exists('generate_slug')) {
    function generate_slug($string) {
        return strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string), '-'));
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Open composer.json and load the helper file.

You must load the helper file using Composer's autoload functionality in order for Laravel to recognise it. In the autoload section of your composer.json file, add the following:

"autoload": {
    "files": [
        "app/Helpers/helpers.php"
    ]
}
Enter fullscreen mode Exit fullscreen mode

After adding the helper file, run the following command to update Composer’s autoload files:

composer dump-autoload
Enter fullscreen mode Exit fullscreen mode

Step 4: Use Your Custom Helper Functions

Now you can use your helper functions anywhere in your Laravel application:

$price = format_price(1234.56); // Output: ₹1,234.56
$slug = generate_slug("Hello World!"); // Output: hello-world
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more