twitter github codepen dribbble rss

How to Make Helper Functions in Laravel 5

When developing a website with Laravel, sometime we need to create a custom helper function that can be called anywhere in our code. For example, we can make a function that returns our site title.

function site_title() {
    return 'Something';
}

And calling it in our blade template.

<head>
    <title>{{ site_title() }}</title>
</head>

In order to be able do that, we’ll be using files autoloading feature in composer. So, first we need to create a php file that contains our custom function. Let’s call it helpers.php. We can put it in any folder we like, I personally like to put it in the app folder. And then, in our composer.json add this property in the autoload section.

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

It should become like this :

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

Lastly, run composer dump-autoload in your terminal and you are good to go. Keep in mind that your functions will become a global functions, so be wise when naming your functions. I always use prefix in all my global functions to avoid name collision with the php or laravel functions.