Search code examples
phplaravel

Custom helper not working in laravel, it return undefined function in controller


Edit For those who may bump into this thread with similar error Remove the namespace from the helpers.php file as it is not a class.

In my own case, the correct code should be

use Illuminate\Http\Request;
use App\Models\User;
use Session;




function showTest(){
    return "test";
}

..and not

namespace App\Helpers;

use Illuminate\Http\Request;
use App\Models\User;
use Session;




function showTest(){
    return "test";
}

Original Question

I am looking to write a global function in laravel using the helper.

Here is my code helpers.php

namespace App\Helpers;

use Illuminate\Http\Request;
use App\Models\User;
use Session;




function showTest(){
    return "test";
}

Composer.json

"autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        },

        "files":[
            "app/Helpers/helpers.php"
        ]
    },

But when i call the function in the controller it returns error;

dd(showTest());

it returns this error;

Call to undefined function App\Http\Controllers\User\showTest()

What could be the problem?

Also I have ran composer dump-autoload

Modified

I have tried all solutions posted here but it’s not working.

Php 8 Laravel 9


Solution

  • Another way of doing this is to register your Helper files in Laravel's service container.

    You could either do this in an existing service provider file, or create a new one, for example HelperServiceProvider.php (can be done with php artisan make:provider)

    In the register method of the service provider, you can take your helper file and require them globally, as such

    public function register()
    {
        require_once(glob(app_path().'/Helpers/helpers.php');
    }
    

    If you have multiple files, you can simply put them in a for each

    public function register()
    {
        foreach (glob(app_path().'/Helpers/*.php') as $filename){
            require_once($filename);
        }
    }