How can I autoload a custom class in Laravel 5.1?

34,330

Solution 1

Your autoloading configuration is almost good, but you have

  • got the namespaces wrong
  • got the paths wrong

To fix the problem, adjust your autoloading configuration:

{
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    }
}

Then rename the directory /library to /Library (note the case).

Then rename the file /app/Library/helper.php to /app/Library/MyHelper.php (note how class name should match the file name).

Then adjust the namespace of the class provided by /app/Library/MyHelper to match the PSR-4 prefix (and thus the structure of your project), as well as usages of the class:

namespace App\Library;

class MyHelper 
{
    public function v($arr)
    {
        var_dump($arr);
    }
}

For reference, see:

Solution 2

Use files directive in composer.json: https://getcomposer.org/doc/04-schema.md#files

{
    "autoload": {
        "files": ["app/library/helper.php"]
    }
}

Solution 3

Use composer.json :

   "autoload": {
    "classmap": [
        "database",
        "app/Transformers"
    ]
 },

Add your auto load directories like I added app/Transformers.

Don't Forget to add run composer dump-autoload.

The only problem with this method is you need to run composer dump-autoload whenever you add new class do that directory.

Or You can use "Files" in composer.json.

"autoload": {
    "files": ["src/MyLibrary/functions.php"]
}
Share:
34,330
GerBawn
Author by

GerBawn

Updated on July 09, 2022

Comments

  • GerBawn
    GerBawn almost 2 years

    I've created a library folder within the app folder to add my own classes.

    enter image description here

    This is the content of the file app/library/helper.php:

    <?php
    
    namespace Library;
    
    class MyHelper
    {
        public function v($arr)
        {
            var_dump($arr);
        }
    }
    

    I added the namespace to composer.json:

    enter image description here

    and then I ran

    $ composer dump-autoload
    

    but it does not seem to have any effects.

    The files

    • vendor/composer/autoload_psr4.php
    • vendor/composer/autoload_classmap.php

    did not change.

    If I try to create an instance of MyHelper, Laravel reports the following error:

    enter image description here

    I'm not sure what I am doing wrong.

  • localheinz
    localheinz over 6 years
    No, it says App\Library.
  • Zachary Weixelbaum
    Zachary Weixelbaum over 6 years
    Oh I didn't realize you used lower case. In Laravel it will recognize both upper case and lower case for the file structure. I have had a folder called library and namespace Library and it worked