How to Create Custom Helper Functions in Laravel
Ankit Verma

Ankit Verma @ankitvermaonline

About: Full Stack Developer 7+ years of experience in Web development, specializing in PHP frameworks.

Location:
Lucknow
Joined:
Sep 18, 2023

How to Create Custom Helper Functions in Laravel

Publish Date: Feb 20
0 0

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

Comments 0 total

    Add comment