Saturday, 31 October 2020

Create Custom Laravel Helpers

Laravel Provider a lot of helper functions for Arrays & Objects, Strings, Fluent Strings, Miscellaneous, and the most used helper function dd().

Step 1: Define Your Helper Functions

To define helpers in laravel create a php file and define a class with methods in it
and place the file at app/helpers.php folder in your laravel application.For example

<?php
namespace App\Helpers;

class MyCustomHelper
{
    public static function formatDateTime($dateTime)
    {
        return $dateTime->format('Y-m-d H:i:s');
    }
}

Step 2: Autoload Your Helpers File


If we want to make laravel helper avaible in laravel then we need to update add details
of any custom helper in composer.json.

Add the following line to the autoload section:

"autoload": {

       "files": [ "app/helpers.php" ],

        "psr-4": {

            "App\\": "app/",

            "Database\\Factories\\": "database/factories/",

            "Database\\Seeders\\": "database/seeders/"

        }

    },

    "autoload-dev": {

        "psr-4": {

            "Tests\\": "tests/"

        }

    },


After adding this line, run composer dump-autoload in your terminal to refresh the autoloaded files.

Step 3: Use Your Custom Helper Functions

After adding up the helper file in composer.json we need to the following command

composer dump-autoload


And afterword we need to use the newly create custom heper in our laravel.For example


use App\Helpers\CustomHelper;

echo CustomHelper::formatDateTime(now());


No comments:

Post a Comment

Laravel csrf token mismatch for ajax post request

Error "CSRF Token Mismatch" commonly occurs if tokens do not match in both sessions and sent , and received requests.CSRF token he...