phplaravelnamespacesautoloadpsr-4

psr-4 autoloading issue in Laravel


Probably this has been answered several times before. I am trying to run autoloader through composer in Laravel.

I am getting this error while running composer dump-autoload

Class App\Admin located in C:/xampp/htdocs/test/app\Models\Admin.php does not comply with psr-4 autoloading standard. Skipping.

I have checked the capitalisation in filesystem and looks ok to me.

Composer version is 2.0.14 which is latest.

Composer.json --

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

Folder structure is:

<root_project>
 app
  Models
   Admin.php
   .....
 config
 public
 ...

app/Models/Admin.php :

namespace App;

use ....
use ....

class Admin extends Authenticatable implements HasMedia
{
......

Please any help is highly appreciated.


Solution

  • The namespace is wrong in your model, you're missing the sub-namespace of Model and have only the vendor namespace, which in the Laravel framework is set to App, pointing to the app folder as its base.

    Changing your Admin models namespace to include the sub-namespace will fix your issue.

    namespace App\Models;
    
    class Admin {}
    

    This is because PSR-4 works off of file paths, with sub-namespaces being directories to travel through to reach the destined class and those directories must match the cases of the sub-namespaces. The same goes for class names, the file must match that of the class, for instance.

    IF your base directory is /src, linked to the vendor namespace Mitra, a class in the root folder of /src will only have the namespace Mitra. IF you have a folder in the root; /src/Models THEN the namespace would be Mitra\Models.

    The specification for PSR-4 is a rather short specification and is very well documented, I recommend reading it if you're having trouble understanding.