Backend Development 6 min read

Creating Custom Helper Functions in Laravel 11

This tutorial walks through installing Laravel 11, creating a helpers.php file with reusable functions, registering it via composer.json, adding a route to test the helpers, and finally running the application, providing a complete guide to enhancing code reuse and maintainability in a Laravel backend project.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Creating Custom Helper Functions in Laravel 11

Laravel, as an excellent PHP framework, greatly simplifies web development complexity. By creating custom helper functions, you can further improve coding efficiency and make the development experience smoother.

In the following sections, we will gradually build a custom helper function usable in Laravel. After completion, you will be able to call this function anywhere in a Laravel 11 application, greatly enhancing code reusability and maintainability.

Step 1: Install Laravel 11

In this step, we will install a Laravel 11 application by executing a specific command.

composer create-project laravel/laravel laravel-11-example

Step 2: Create helpers.php file

Next, we need to create a file named helpers.php and define some useful functions in it. This file will be placed in the app/Helpers directory, allowing convenient organization and management of helper functions that can be called throughout the application.

Path: app/Helpers/helpers.php

In this file you can write various helper functions such as date formatting, string manipulation, array handling, etc., which can be called from any location in your application, improving code reuse and maintainability.

Make sure after creating helpers.php to set its namespace and access permissions correctly so other files can reference and use the functions. This enables you to fully leverage the helper functions provided by helpers.php , simplifying code and improving quality and readability.

<?php
   
use Carbon\Carbon ; 
  
/** 
* Write code on Method
* 
* @return response() 
*/ 
if (! function_exists('convertYmdToMdy')) {
    function convertYmdToMdy($date)
    {
        return Carbon::createFromFormat('Y-m-d', $date)->format('m-d-Y');
    }
}
  
/** 
* Write code on Method
* 
* @return response() 
*/ 
if (! function_exists('convertMdyToYmd')) {
    function convertMdyToYmd($date)
    {
        return Carbon::createFromFormat('m-d-Y', $date)->format('Y-m-d');
    }
}

Step 3: Register the file path in composer.json

In this crucial step, we will specify a clear path for the helper file. Follow these steps:

Open the composer.json file in the project root with a text editor.

In the composer.json file, locate an appropriate place to add the file path registration, typically within the autoload or scripts section, depending on your project needs.

Add the necessary code snippet to register your helper file path, usually specifying the namespace, path, and possibly the file extension.

Save and close the composer.json file.

Ensure you follow Composer's conventions when adding the path and that it points to the correct file or directory. This allows Composer to locate and use the helper files when you run Composer commands.

"autoload": {
            "psr-4": {
                "App\\": "app/",
                "Database\\Factories\\": "database/factories/",
                "Database\\Seeders\\": "database/seeders/"
            },
            "files": [
                "app/Helpers/helpers.php"
            ]
        },

Then run the following command to load the helper.php file.

composer dump-autoload

Step 4: Add route

Now we will define a route in the web.php file.

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
    
Route::get('date-convert', function(){
  
    $mdY = convertYmdToMdy('2024-03-27');
    var_dump("Converted into 'MDY': " . $mdY);
  
    $ymd = convertMdyToYmd('03-27-2024');
    var_dump("Converted into 'YMD': " . $ymd);
});

Step 5: Run the Laravel application

Then, use the following command to run the Laravel application.

php artisan serve
Backend DevelopmentPHPComposerLaravelhelper functions
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.