1

My function is like this :

function romanic_number($integer, $upcase = true) 
{ 
    $table = array('M'=>1000, 'CM'=>900, 'D'=>500, 'CD'=>400, 'C'=>100, 'XC'=>90, 'L'=>50, 'XL'=>40, 'X'=>10, 'IX'=>9, 'V'=>5, 'IV'=>4, 'I'=>1); 
    $return = ''; 
    while($integer > 0) 
    { 
        foreach($table as $rom=>$arb) 
        { 
            if($integer >= $arb) 
            { 
                $integer -= $arb; 
                $return .= $rom; 
                break; 
            } 
        } 
    } 

    return $return; 
} 

I want in view, I can accessing like this :

{{ romanic_number(2) }}

The result : II

Where I put my custom functions to be accessed in view?

I try put my custom functions in controller, but it's failed

UPDATE

I make folder helpers in folder app. Then I make file helper.php in folder Helpers (mysystem/app/Helpers/helper.php)

I put this :

<?php

if (! function_exists('romanic_number')) 
{
    function romanic_number($integer, $upcase = true) 
    { 
        ...

        return $return; 
    } 
}

I add "app/Helpers/helper.php" in composer.json like this :

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

Then I run composer dump-autoload

There exist error like this :

Call to undefined function romanic_number() (View: C:\xampp\htdocs...
moses toh
  • 12,344
  • 71
  • 243
  • 443

3 Answers3

3

Create a file named helpers.php in folder app/Helpers (first you have to create Helpers folder), put all your functions in that file.

Then tell the composer about this file in composer.json as:

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

Then do composer dump-autoload and you can use it in your view or anywhere else.

For example in view:

{{ romanic_number(2) }}
Amit Gupta
  • 17,072
  • 4
  • 41
  • 53
2

You can create custom helpers.php file and define all helpers there:

if (! function_exists('romanic_number')) {
    function romanic_number($value)
    {
        $romanic = ....;
        return $romanic;
    }
}

And then add it to composer.json so Laravel could autoload it:

"autoload": {
    ....
    "files": [
        "app/someFolder/helpers.php"
    ]
},
Community
  • 1
  • 1
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
1

You can create your own custom helpers. Create CustomHelper.php file and add your function there & include in composer.json file as below

"autoload": {
        ...
        "psr-4": {
             "App\\": "app/"
        },
        "files" : [
            "app/CustomHelper.php"
             ...
        ]
}
Saumini Navaratnam
  • 8,439
  • 3
  • 42
  • 70