How to create helper functions in Laravel

How to create helper functions in Laravel

Here explained how to create helper functions in Laravel.

Helper functions are functions that perform common tasks or simplify your code in Laravel. Laravel provides many helper functions for different purposes, such as working with arrays, strings, URLs, files, etc.

However, sometimes you may need to create your own helper functions for your specific needs or preferences

For example, you may want to create a function that generates a random code or converts a string to uppercase. To create your own helper functions in Laravel, you can follow these steps:

1: Create a helper custom class and add namespace. File at app\Helpers\Helper.php

<?php 
namespace App\Helpers;
class Helper
{
    public static function upperCase(string $string)
    {
        return strtoupper($string);
    }
}

2 : Create alias within config/app.php

 'aliases' => [
     ...
        'Helper' => App\Helpers\Helper::class,
     ...

3: Run composer dump-autoload in the project root

4: For blade templates use as described below.

{!! Helper::upperCase('coding solutions point') !!}

For additional use anywhere in laravel you can use this alias in your controller and call as below.

use Helper;
class MyController extends Controller
{
    public function __construct()
    {
        Helper::upperCase('coding solutions point');
    }
    ...