1

I have custom class in path:

app/Http/Helpers/Helper/Helper.php 

with namespace is: namespace App\Helpers;

It has a static method:

public static function getMonthName($monthNumber)
{
    return date("F", mktime(0, 0, 0, $monthNumber, 1));
}

I tried to call this method from template Laravel:

{{ \App\Http\Helpers\Helper::getMonthName($i) }}

But it does not work:

Class 'App\Http\Helpers\Helper' not found
3
  • Reference the namespace App\Helpers\Helper::getMonthName($i) or update your namespace to namespace App\Http\Helpers; should do the trick Commented Mar 23, 2018 at 14:23
  • your namespace and reference diffferes!! Commented Mar 23, 2018 at 14:23
  • ``` Call to undefined method App\Helpers\Helper::getMonthName() ``` Commented Mar 23, 2018 at 14:30

4 Answers 4

3

update the namespace to be :

namespace App\Http\Helpers\Helper;

namespace must be the same as the class path, because laravel uses spl_autoload to load classes dynamically

Sign up to request clarification or add additional context in comments.

2 Comments

Then in template how? {{ Helper::getMonthName($i) }}?
in template : {{ App\Http\Helpers\Helper\Helper::getMonthName($i) }}
1

Do it like everyone else, make helpers.php (in root, where .env file is).

if (! function_exists('get_month_name')) {
    function get_month_name(int $month)
    {
        return date('F', mktime(0, 0, 0, $month, 1));
    }
}

and in your composer.json autoload it:

"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "helpers.php"
    ]
},

now you are able to call your helper function everywhere in code base

Comments

1

If someone is trying out to use helpers function in a blade make sure you do the following things.

//composer.json

"files":[
        "app/Helpers/Helper.php"
 ],


//app.php

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

and in your blade you could use if Helper.php are static functions

{{ Helper::getStatusColor($item->status) }}

1 Comment

'App\Helpers\Helper::class', probably this doesn't need quotation.
1

Best to add it to your config/app.php.

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

1 Comment

This has already been mentioned in Abhi's answer. When answering older questions that already have answers, please make sure you provide either a novel solution or a significantly better explanation than existing answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.