Search code examples
phplaravel

Moving Laravel models back to the App/ folder root


In Laravel 8 there was a shift to put models into their own App/Models folder after they were moved to the App/ root in Laravel 5.

However Laravel has always supported the ability to switch back for those who preferred it.

I learned Laravel with version 5, so I prefer models being in the App/ root.

How can I move models back to where they were in Laravel 5-7 and still have Laravel 10+ function correctly?


Solution

  • The steps for putting models back in the App/ root are very minimal, and Laravel will detect you've done them so make:model will work as expected.

    1. Edit config/auth.php so that the users model entry points to the correct namespace:

       'users' => [
           'driver' => 'eloquent',
           'model' => App\User::class,
       ],
      
    2. Move your Users.php model (and any other models you have) into the App/ root. Then delete the models directory.

    3. Once they're moved, ensure the namespace is correct for each of the models.

       namespace App;
      

    That's all you need to do!

    To test it's worked correctly, you can ask PHP Artisan to create a new model for you:

        > php artisan make:model Test
    

    You should see Test.php in the App/ root.


    Important Note: Laravel Breeze doesn't support this out of the box, but the quick fix is to simply search and replace App\Models\User; with App\User;.

    There is one controller (RegisteredUserController.php), one request (ProfileUpdateRequest.php), and six tests that Breeze adds, that will be updated by this search/replace. Very simple.

    If you encounter any problems when running the default tests, make sure you run composer dump-autoload after making the above changes.