Simplest way to create and include a helper functions file in Laravel 6/7/8/9

Helper functions are time saving tools in any application. Laravel comes with many built-in useful PHP functions which may include Array & Objects functions, String functions, URL functions and many more. Please see the complete list before you decide to create your own function. Please note that there is kebab_case to do the similar thing which my function does in this example.

Helper functions in laravelHere is the quickest method to create and automatically include your functions file in your app.

STEP 1

Create a functions file and place it in /Helpers. For example I created a new function file with the name functions.php

if(!function_exists('slugify'))  {
    function slugify($text)
    {
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
        $text = preg_replace('~[^-\w]+~', '', $text);
        $text = trim($text, '-');
        $text = preg_replace('~-+~', '-', $text);
        $text = strtolower($text);
        return $text;
    }
}

STEP 2

Open composer.json which is found in root folder. Look for "autoload": {. Add the following to look it like:

"autoload": { 
    "files": [ "app/Helpers/functions.php" ],
    ...

STEP 3

In command line, run:

composer dumpautoload

Now you should be able to use slugify function or any other functions placed in functions.php file anywhere in your application.

There are other methods to create and include custom helper function files and this tutorial explain it in detail.

Note: There is a kebab_case function in Laravel to do similar what our slugify function doing here. Check useful functions in laravel for more details.

Leave a Reply