3
votes

I have created app/Http/helpers.php

if (!function_exists('getLocation')) {
function getLocation($request)
{
    return 'test';
}

I have added files section in composer.json autoload

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

Here is my controller :

namespace App\Http\Controllers;

use App\Jobs\ChangeLocale;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;
use Log;

class HomeController extends Controller
{
     public function index(Request $request)
     {  
          $data['location'] = getLocation($request);

     }

}

When I call the function in controller as getLocation($request); it is saying "Call to undefined function App\Http\Controllers\getLocation()"

This is working fine in my local , but not on remote server. What am I missing in my remote server. Tried composer install and composer dump-autoload.

UPDATE: The helper file is not getting listed in vendor/composer/autoload_files.php

3
could you post some more information like controller snippet from server? from what I've gathered from this it's probably something stupid like you've forgot to update some file or import namespace. - boroboris
Added controller, but it is working in my local and error on server. - Mirza Vu
from my expirience, when that happens (server-localhost difference) it is something you have different in those two environments. Either the helpers file missing, different composer files... - boroboris

3 Answers

2
votes

On server, you need to execute:

composer dumpautoload

because it is not found on vendor/autoload.php

0
votes

Try like this,

  1. create Helpers directory inside the app directory.
  2. create a Example.php file inside the Helpers directory
  3. create a alieas for this file at config/app.php file

    Ex: 'Example' => App\Helpers\Example::class,

The code in the Example.php like follows,

<?php 

namespace App\Helpers;

class Example
{   
    static function exampleMethod()
    {
       return "I am helper";
    }
}

Using the above Example helper in Controller files like follows,

<?php

namespace App\Http\Controllers;
use App\Helpers\Example;

class HomeController extends Controller
{
     public function index(Request $request)
     {  
          return Example::exampleMethod();

     }

}

Using the above Example helper in blade view files like follows,

<div>{{ Example::exampleMethod()}}</div>

This will help you to get solution.

0
votes

Make Sure the structure of the Helper.php is correct...

<?php

//no namespace, no classes
//classes are not helpers

if ( !function_exists('nextStage') ) {
    function nextStage($currentStage) {
        //if you need to access a class, use complete namespace
        return \App\Models\Stage::where('id',$currentStage)->first()->next_stage;
    }
}

More help on Laracast found here