Home » Php » php – Move Laravel 5 Eloquent models into its own directory

php – Move Laravel 5 Eloquent models into its own directory

Posted by: admin April 23, 2020 Leave a comment

Questions:

Laravel 5 has ORM models by default in app folder. I want to move these into app/models. When I do that then these classes are not found anymore.

How to make Laravel find the Eloquent ORM models from app/models?

How to&Answers:

Just create a folder named Models and move your files into it. After that, change the namespace of the models from just App to App\Models (update the usages as well) and run composer dump-autoload.

Answer:

Solution for Laravel 5.6+


1. Move the files to the new directory

Say you want to move the models to app/Models

2. Change the namespace of the models

For each model change :

namespace App;

to

namespace App\Models;

3. Change the references in other files

Check these files and search especially app\User

  • app/Http/Controllers/Auth/RegisterController.php
  • config/auth.php
  • config/services.php
  • database/factories/ModelFactory.php
  • database/factories/UserFactory.php
  • Your Controllers

And change App/ModelExample to App/Models/ModelExample

4. Autoload files

Run composer dump-autoload

5. Congratulations!

Answer:

Add "app/models" to composer.json’s classmap autoload section

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

Answer:

Afer moving all files in the models folder. What you need to do is run:


composer dump-autoload

This worked for me. 🙂

Answer:

After doing @Saint Play steps. I had to do php artisan config:clear. Then it worked !