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
CodePudding user response:
You need to run composer dump-autoload
and it will work.
For more details click here
CodePudding user response:
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);
}
}
CodePudding user response:
First I want to apologize for all the troubles.
The problem was that I used namespace in my helpers.php file
This thread saved me
https://stackoverflow.com/a/29736097/14940381
CodePudding user response:
Try loading them inside AppServiceProvider boot method instead of composer file.
require_once app_path('Helpers/helpers.php');
CodePudding user response:
composer.json
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
},
"files":[
"app/Helpers/helpers.php",
"app\\Helpers\\helpers.php",
]
},
hepler.php
<?php
if(!function_exists('showTest')){
function showTest()
{
return "test";
}
}
if(!function_exists('showTest2')){
function showTest2()
{
return "test 2";
}
}
And run composer dump-autoload
CodePudding user response:
You should keep all functions of helper files into a helper class. It should be like,
namespace App\Helpers;
use Illuminate\Http\Request;
use App\Models\User;
use Session;
class HelperClass {
function showTest(){
return "test";
}
}
And then use can add namespace like App\Helpers\HelperClass
. It should work.
Thanks:)