Hello Developer, in this tutorial, we will teach you how to create custom helpers in laravel. we will give you step by step instruction of how to create custom helper functions in laravel and how to call these functions anywhere in laravel application.

In laravel custom helper, you can create your own helper and call anywhere like models, controller, route, blade view etc in laravel application.

Step 1 – Create Helper File

Create a helper file in your preffered location but within the context of a Laravel application.
we prefer to keep in app/helpers.php in the root of the application.

<?php
// Custom Helper by Nisar Ahmed

if (!function_exists('success')) {
    /**
     * // Success Message
     *
     * @param $msg
     * @return session with success
     */
    function success($msg)
    {
        return request()->session()->flash('success', $msg);
    }
}

if (!function_exists('error')) {
    /**
     * // Error Message
     *
     * @param $msg
     * @return session with success
     */
    function error($msg)
    {
        return request()->session()->flash('error', $msg);
    }
}

if (!function_exists('uniqueString')) {
    /**
     * Generate Unique String with Model
     *
     * @param $table
     * @param $key
     * @param $length
     * @param $numbers
     * @return null
     */
    function uniqueString($table, $key, $length = 8, $numbers = false)
    {
        if ($numbers) {
            // generate only numbers
            $unique_id = mt_rand(100000000000, 999999999999);
        } else {
            $unique_id = \Illuminate\Support\Str::random($length);
        }
        
        $d = \DB::table($table)->where($key, $unique_id)->first();
        if ($d) {
            $this->unique_string($table, $key, $length, $numbers);
        } else {
            return $unique_id;
        }
        
    }
}

Step 2 – Autoloading

To use your custom helper functions, you have to put path of helpers file into composer.json to load them into your application at runtime.

"autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
        "files": [
            "app/helpers.php"
        ]
    },

After adding a new path to the files array, you need to dump the autoloader by running the following command in the terminal.

composer dump-autoload

Now you can run your custom helper functions in your inside your application.

Example

// Generate Unique String 

$image = uniqueString('users','username');

This will generate and match the generated string with the user table against the username field then it will return only if its unique.

Author

I am a Laravel developer with some other skills.

Write A Comment