Ad

Creating A Custom Helper In Own Package In Laravel

- 1 answer

I am writing a new composer package to be used in laravel, in which I want to define my own helper function (the helper is defined in my own module, not in the laravel, but to be used by laravel - see the helpers.php in the tree below).

This is the packages folder tree of my module in the root of a fresh laravel project:

└───majidalaeinia
    └───favicon
        │   composer.json
        │
        ├───src
        │   │   FaviconServiceProvider.php
        │   │
        │   ├───app
        │   │       helpers.php
        │   │
        │   └───routes
        │           web.php
        │
        └───vendor
            │   autoload.php
            │
            └───composer
                    autoload_classmap.php
                    autoload_files.php
                    autoload_namespaces.php
                    autoload_psr4.php
                    autoload_real.php
                    autoload_static.php
                    ClassLoader.php
                    installed.json
                    LICENSE

Here is the majidalaeinia/favicon/composer.json content:

{
    "name": "majidalaeinia/favicon",
    "description": "This is an educational package on favicon.",
    "license": "MIT",
    "authors": [
        {
            "name": "Majid Alaeinia",
            "email": "[email protected]"
        }
    ],
    "minimum-stability": "dev",
    "require": {},
    "autoload": {
        "psr-4": {
            "majidalaeinia\\favicon\\": "src/"
        },
        "files": [
            "src/app/helpers.php"
        ]
    }
}

And here is the composer.json of the laravel project itself:

// ...
"autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/",
            "majidalaeinia\\favicon\\": "packages/majidalaeinia/favicon/src"
        }
    },
// ...

I have defined a helper in majidalaeinia/favicon/src/app/helpers.php and have tried composer dumpautoload command on laravel route and my own project and get no error, but can not see the result of my helper which is a simple dd() right now.

I get this error:

Call to undefined function testtt() (View: D:\projects\favicon\resources\views\welcome.blade.php)

What can I do to use my custom helper in my module in laravel project?

Ad

Answer

Could not solve it by composer independently and used my package service provider. I added this code to the boot() method of my FaviconServiceProvider and it works now:

if (File::exists(__DIR__ . '\app\helpers.php')) {
            require __DIR__ . '\app\helpers.php';
        }
Ad
source: stackoverflow.com
Ad