How to create Helpers function in Laravel 8

  964 views   1 year ago Laravel

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": [
    "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.


 * 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 {

        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>
    <meta charset="utf-8">
    <div class="container m-3">
        <div class="row">
            <p>Launching soon {{ timeElapsedString(date('2021-07-01 23:59:59')) }}</p>

I hope it will help you.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]