Latest Posts

Creating helper functions in Laravel

Quick Tips

A quick tip for adding globally available 'helper methods' in Laravel


Often, you need to reach in to the tool chest to pull out your commonly used functions. You don't want to repeat your code, so why not create a helpers PHP file that contains a list of your functions.

You can store this wherever you like, but I'd recommend keeping it inside your app directory and name the file simply helpers.php. This file doesn't have to be namespaced, but it does need to be loaded by composer.

helpers.php

<?php
	
if (!function_exists('exampleFunction')) {
	function exampleFunction(string $value) {
		dd("We received $value");
	}
}

Note that it's important to make sure you wrap your function with a check to make sure it's not going to conflict with anything - as these functions aren't namespaced.

Once you've established your helper file, you can now tell composer where it is and how to load it in. You can do this by adding a files array into the autoload section of your composer.json file.

composer.json

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        ...
    },
    "require-dev": {
        ...
    },
    "autoload": {
        "files": [
            "app/helpers.php"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
		...
}

Don't forget to composer dump-autoload so that Composer reads your file in and you're good to go! You can now call your helper functions wherever needed throughout your application. This is great for common functions, custom exception handling and much more!