Refactoring Laravel models into a dedicated folder

Improve the organisation of your projects

May 2020

Update: This is now the default since Laravel 8

Out of the box, Laravel adds all models to the App folder. This is fine at the start, but can quickly become unorganised as the number of models grows. This isn't ideal as the App folder is one that you will be commonly browsing as it contains controllers and other important files.

The first thing I like to do after a fresh Laravel install is to create a folder for models in the App directory. Laravel expects models to be in the App namespace so there are a number of references that need to be updated.

# Create fresh Laravel app with authentication
laravel new blog --auth

# Create Models folder
mkdir app/Models

# Move User model into new folder
mv app/User.php app/Models

At this point you can manually move all your other models if you aren't working on a fresh project.

In order to avoid namespace errors you will need to update the namespace for all models in the project. A search and replace is usually the best approach.

app/Models/User.php

namespace App\Models;

Remember to update all Use statements in the project as well:

app/Http/Controllers/Auth/RegisterController.php

use App\Models\User;

The default authentication will also need to be updated in a number of other locations:

config/auth.php

'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\Models\User::class,
    ],
],

database/factories/UserFactory.php

use App\Models\User;

Now, when creating new Models we can use the new namespace to generate models properly:

php artisan make:model Models/Post

The above approach can be used for generating anything; here's an example for a new controller:

php artisan make:controller PostController --model=Models/Post

And finally, remember to refresh composer references:

composer dump-autoload

That's all there is to it, and now all models are nicely organised into a dedicated folder.


Sign up for my newsletter

Get notified when I post a new article. Unsubscribe at any time, and I promise not to send any spam :)

© Steven Cotterill 2021