Laravel 9 Create Custom Helper Functions Example (ok)

https://www.itsolutionstuff.com/post/laravel-9-create-custom-helper-functions-exampleexample.html

C:\xampp\htdocs\test\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');
  }
}

C:\xampp\htdocs\test\composer.json

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "require":
    {
        "php": "^7.3|^8.0",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.75",
        "laravel/sanctum": "^2.11",
        "laravel/tinker": "^2.5"
    },
    "require-dev":
    {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.4",
        "nunomaduro/collision": "^5.10",
        "phpunit/phpunit": "^9.5.10",
        "sven/artisan-view": "^3.4"
    },
    "autoload":
    {
        "psr-4":
        {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        },
        "files": [
            "app/Helpers/helpers.php"
        ]
    },
    "autoload-dev":
    {
        "psr-4":
        {
            "Tests\\": "tests/"
        }
    },
    "scripts":
    {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-update-cmd": [
            "@php artisan vendor:publish --tag=laravel-assets --ansi --force"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    },
    "extra":
    {
        "laravel":
        {
            "dont-discover": []
        }
    },
    "config":
    {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "minimum-stability": "dev",
    "prefer-stable": true
}

C:\xampp\htdocs\test\routes\web.php

<?php
// use App\Http\Controllers\UserController;
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('/', function () {
  return view('welcome');
});
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);
});

C:\xampp\htdocs\test\resources\views\welcome.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laravel</title>
</head>
<body class="antialiased">
  <div class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center py-4 sm:pt-0">
    @if (Route::has('login'))
    <div class="hidden fixed top-0 right-0 px-6 py-4 sm:block">
      @auth
      <a href="{{ url('/home') }}" class="text-sm text-gray-700 dark:text-gray-500 underline">Home</a>
      @else
      <a href="{{ route('login') }}" class="text-sm text-gray-700 dark:text-gray-500 underline">Log in</a>
      @if (Route::has('register'))
      <a href="{{ route('register') }}" class="ml-4 text-sm text-gray-700 dark:text-gray-500 underline">Register</a>
      @endif
      @endauth
    </div>
    @endif
    <div class="max-w-6xl mx-auto sm:px-6 lg:px-8">
      <p>Date: {{ convertYmdToMdy('2022-02-12') }}</p>
      <p>Date: {{ convertMdyToYmd('02-12-2022') }}</p>
    </div>
  </div>
</body>
</html>

Hi,

Today, I would like to show you laravel 9 create custom helper functions. This post will give you a simple example of laravel 9 creating a global function. We will look at an example of laravel 9 create a custom helper file. Here you will learn laravel 9 to create a global helper file.

we know Laravel 9 also provides helper functions for array, URL, route, path, etc. but sometimes we may require more custom helper functions for our project. so we need to create our own custom helper file and define global functions that can easily use it.

Here, I will give you a few steps to show you how to create a custom helper function in laravel 9.

Step 1: Install Laravel 9

This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create helpers.php File

In this step, you need to create app/Helpers/helpers.php in your laravel project and put the following code in that 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');    }}

Read Also: Laravel Phone Number Verification using Firebase Example

Step 3: Register File Path In composer.json File

In this step, you have to put path of helpers file,so basically open composer.json file and put following code in that file:

composer.json

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

After register, we need to run composer auto load command so that will load our helper file.

next run bellow command:

composer dump-autoload

Step 4: Add Route

Next, You have to open and update the following routes in the routes/web.php file.

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:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

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:

You can also use in blade file as like bellow:

Read Also: Laravel 9 Eloquent Mutators and Accessors Example

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

I hope it can help you...

Last updated