Functions Guide | John
LARAVEL

Laravel Custom Helpers and Functions Guide

February 15, 2024 11 min read

Introduction

Custom helpers in Laravel allow you to create reusable functions that can be accessed throughout your application. They help reduce code duplication and keep your codebase clean and maintainable.

Creating Helpers

Create a helpers file in your app directory:

// app/Helpers/helpers.php
<?php

use Illuminate\Support\Str;

if (!function_exists('format_currency')) {
    function format_currency($amount, $currency = 'USD')
    {
        $symbols = [
            'USD' => '$',
            'EUR' => '€',
            'GBP' => '£',
        ];
        
        $symbol = $symbols[$currency] ?? '$';
        return $symbol . number_format($amount, 2);
    }
}

if (!function_exists('slugify')) {
    function slugify($string)
    {
        return Str::slug($string);
    }
}

Loading Helpers

Register the helpers file in composer.json:

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

Then run:

composer dump-autoload

Helper Examples

// Date formatting helpers
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y')
    {
        return \Carbon\Carbon::parse($date)->format($format);
    }
}

// User helpers
if (!function_exists('current_user')) {
    function current_user()
    {
        return auth()->user();
    }
}

// Array helpers
if (!function_exists('array_get')) {
    function array_get($array, $key, $default = null)
    {
        return data_get($array, $key, $default);
    }
}

// View helpers
if (!function_exists('meta_title')) {
    function meta_title($title = null)
    {
        static $title = '';
        
        if ($title) {
            return $title . ' - ' . config('app.name');
        }
        
        return $title ?: config('app.name');
    }
}

Best Practices

  • Namespace functions - Group related helpers logically
  • Use function_exists - Prevent redeclaration errors
  • Type hinting - Add return types for better IDE support
  • Document helpers - Add PHPDoc comments
  • Consider facades - Complex logic may warrant a service class

Summary

Custom helpers are a powerful way to share common functionality across your Laravel application. By creating well-organized helper files, you can simplify your code and reduce repetition.

For more information, check out our other tutorials on View Components and Mailables.