How to create custom helper in Laravel?

Posted by LaravelIndia - 6 months ago

Step 1: Create helpers.php File

Path : app/Http/helpers.php

function convertDateFormate($date,$date_format){
    return \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format($date_format);  
}
function getLogoPath($image_name)
{
    return public_path('uploades/logos/'.$image_name);
}

Step 2: Add File Path In composer.json File Path : composer.json

"autoload": {
    "classmap": [
        ...
    ],
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/Http/helpers.php" //simple Add This Line
    ]
},

Step 3: Run Command

composer dump-autoload

Example :

$logoName = 'myweblogo.png';
$fullpath = getLogoPath($logoName);
dump($fullpath);
//AND
{{ convertDateFormate(date('Y-m-d H:i:s'),'d-m-Y')  }}