How to Create Custom Helper Functions in LARAVEL 10

Spread the love

Hi Guys!

In this comprehensive article, we will guide you on how to create custom helper functions for Laravel 10, focusing on the keyword “Create Custom Helper.” Discover how to craft global functions in Laravel 10, specifically tailored to your needs. Let’s dive into the process of creating custom helper files in Laravel 10.

Laravel 10 offers a wide array of built-in utility functions, including those for arrays, URLs, routes, paths, and more. However, there are times when your project requires unique assistance functions. In such cases, it’s essential to design your own custom helper file and define global functions that seamlessly integrate with it.

In this tutorial, we’ll provide you with step-by-step guidance on constructing a distinctive helper function in Laravel 10, all centered around the “Create Custom Helper” concept.

Step 1: Install Laravel 10

While it’s not mandatory, you can still go ahead and execute the following command if you haven’t yet established your Laravel application:

Also Read: How to Add Foreign Key in MIGRATION using Laravel?

composer create-project laravel/laravel example-app

Step 2: Create Custom Helper: helpers.php File

  1. Begin by generating a file named “app/Helpers/helpers.php” within your Laravel project directory.
  2. Next, insert the provided code snippet into the newly created “helpers.php” file.
app/Helpers/helpers.php
<?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 File Path In composer.json File

To successfully proceed with this task, it’s essential to provide the location of the helpers file. To accomplish this, please follow these steps:

  1. Open the composer.json file.
  2. Insert the following code snippet:

Also Read: How to Rollback Migration in Laravel?

composer.json
...

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

...

After completing your registration, it’s essential to run the composer autoload command to load our helpful file. Next, execute the following command:

composer dump-autoload

Step 4: Add Route

Ensure proper configuration and updates within the routes/web.php file:

  1. Open the routes/web.php file.
  2. Update and configure the following routes accordingly:

Also Read: How to Drop Soft Delete from Table using Migration in LARAVEL?

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
  
Route::get('call-helper', function(){
  
    $mdY = convertYmdToMdy('2022-02-12');
    var_dump("Converted into 'MDY': " . $mdY);
    
    $ymd = convertMdyToYmd('02-12-2022');
    var_dump("Converted into 'YMD': " . $ymd);
});

Run Laravel App:

Once you’ve successfully completed all essential tasks, it’s time to run the following command and hit Enter to initiate the Laravel application:

Execute the following command and press Enter to launch the Laravel application after completing all required steps:

Also Read: How to Use LARAVEL DB Raw Query?

php artisan serve

To access the app’s output, simply insert the given URL into your web browser.

http://localhost:8000/call-helper

Output:

string(32) "Converted into 'MDY': 02-12-2022" 

string(32) "Converted into 'YMD': 2022-02-12"
Use In Blade File:

Moreover, you have the option to employ a blade file, as demonstrated in the following example:

Also Read: How To Send Email In Laravel 9

<p>Date: {{ convertYmdToMdy('2022-02-12') }}</p>

<p>Date: {{ convertMdyToYmd('02-12-2022') }}</p>

Your quest for the best Laravel blog ends here, where expert knowledge meets curated excellence.

Leave a Comment