Create custom helper function in Laravel 8

Laravel ships with rich global function which you can use anywhere in application. Still somewhere in application you need few details at anywhere. You want to run specific code at so many conotrollers and blade files.

For that you don't want tp write same code at everytime. You need to create global function which can be used at anywhere in application. You can do it using composer.

In this article, we will create global method and use it in blade view file.

First of open composer.json file in the root directory of project. Under the "autoload" key, add files array with php file location as below:

"autoload": {
    "files": [
        "app/Helpers/helpers.php"
    ],
    "psr-4": {
        "App\\": "app/",
        "Database\\Factories\\": "database/factories/",
        "Database\\Seeders\\": "database/seeders/"
    }
},

Now add the helper file at app/Helpers/helpers.php. In this file we will define a function.

<?php

/*
 * Function to convert datetime into human readable format
 * timeElapsedString('2013-05-01 00:22:35');              -- 4 months ago
 * timeElapsedString('2013-05-01 00:22:35', true);        -- 4 months ago
 * timeElapsedString('@1367367755'); # timestamp input    -- 4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago
*/
if (!function_exists('timeElapsedString')) {
    function timeElapsedString($datetime, $full = false)
    {
        $now = new DateTime;
        $ago = new DateTime($datetime);
        $diff = $now->diff($ago);

        $diff->w = floor($diff->d / 7);
        $diff->d -= $diff->w * 7;

        $string = array(
            'y' => 'year',
            'm' => 'month',
            'w' => 'week',
            'd' => 'day',
            'h' => 'hour',
            'i' => 'minute',
            's' => 'second',
        );
        foreach ($string as $k => &$v) {
            if ($diff->$k) {
                $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
            } else {
                unset($string[$k]);
            }
        }

        if (!$full) $string = array_slice($string, 0, 1);
        return $string ? implode(', ', $string) . ' ago' : 'just now';
    }
}

At the last, we need to add newly created file into composer file list. Run the command in Terminal or CMD to discover new files.

composer dump-autoload

Now you can use timeElapsedString() method anywhere in the project.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
    <div class="container m-3">
        <div class="row">
            <p>Launching soon {{ timeElapsedString(date('2021-07-01 23:59:59')) }}</p>
        </div>
    </div>
</body>
</html>