phayes0289's avatar

Call to undefined function When Using A Helper File

I have created the following helper fie for use with Spatie

<?php

namespace App\Helpers;

use Spatie\Valuestore\Valuestore;

if (!function_exists('preferences')) {
    function preferences()
    {
        return Valuestore::make(storage_path('app/globalprefs.json'));
    }
}

The globalprefs.json file looks like this:

{
    "show_module_help": true,
    "page_title_prefix": "My App - ",
    "display_todays_date": true,
    "show_rss_feed": false
}

I have added it to the composer.json file as follows:

    "autoload": {
        "psr-4": {
            "App\": "app/",
            "Database\Factories\": "database/factories/",
            "Database\Seeders\": "database/seeders/"
        },
        "files": [
            "app/Helpers/GlobalPreferenceHelper.php"
        ]
    },

When I try to access the value in the stored json file using:

  {{ preferences()->get('show_module_help', false) ? 'checked' : 'not checked' }}

I get:

Call to undefined function preferences()

What am I missing?

0 likes
3 replies
LaryAI's avatar
Level 58

The issue seems to be with the autoloading configuration in the composer.json file.

To fix this, you can try the following steps:

  1. Make sure that the helper file is located at the correct path: app/Helpers/GlobalPreferenceHelper.php.

  2. Run the following command to regenerate the autoloader files:

composer dump-autoload
  1. Verify that the composer.json file has been updated with the correct autoload configuration:
"autoload": {
    "psr-4": {
        "App\": "app/",
        "Database\Factories\": "database/factories/",
        "Database\Seeders\": "database/seeders/"
    },
    "files": [
        "app/Helpers/GlobalPreferenceHelper.php"
    ]
},
  1. Finally, make sure to include the helper file in the file where you are using the preferences() function. For example, if you are using it in a Blade template, you can include the helper file at the top of the template like this:
@php
    require_once app_path('Helpers/GlobalPreferenceHelper.php');
@endphp

After following these steps, the preferences() function should be available for use in your application.

thinkverse's avatar

The helper file is namespaced, so you need to either import it via the use statement, call it via the fully qualified name, or remove the namespace.

use App\Helpers\preferences;

preferences();

// or

App\Helpers\preferences();
Basem's avatar

make sure the files path, and run

composer dump-autoload

Please or to participate in this conversation.