Move laravel eloquent model into Models directory [Step By Step]

move-laravel-model-into-models-directory

Normally when you create model file using artisan command php artisan make:model Test , It will create model file under app directory. Its fine for small projects where only 2 or 3 model files present but when you are developing big application with lot of model files then it is not a good practice.

It should be in separate directory so we can better structure our project.

In this tutorial i will show you how to move laravel eloquent model files into Models directory step by step. You can perform this tutorial on laravel 5.6+ version.

Here we will create Models directory under app folder and move all the models inside it. Lets understand step by step as shown below.

Step 1: Create Models directory under app directory and move all models file in new app\Models directory.

Step 2: Now change namespace of model files

From

<?php

namespace App;

...

To

<?php

namespace App\Models;

...

Step 3: Now change all the references in other files where you have used models

For example, Before moving user model under Models directory we use it as App\User but after moving user model in App\Models directory we will use it as App\Models\User

For App\User model, you have to check and update below files as well. Change App\User to App\Models\User

  • app/Http/Controllers/Auth/RegisterController.php
  • config/auth.php
  • config/services.php
  • database/factories/ModelFactory.php
  • database/factories/UserFactory.php
  • Also update their controllers

Step 4: Autoload files using below composer command

composer dump-autoload

Awesome, you did it.

composer-dump-autoload-output

Now if you want to make new model under Models directory then you can append directory name before model name in artisan command. See below artisan command.

php artisan make:model Models/Task

It will create Task.php model under App\Models directory with appropriate namespace. Check the generated model code by above artisan command.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    //
}

Final Words

I hope that you understand how to move laravel eloquent model files under Models directory step by step. If you have any questions regarding this tutorial, Please write down your doubt in comment. I will help you. Please share this tutorial with your friends.

Reference : https://stackoverflow.com/questions/29052267/move-laravel-5-eloquent-models-into-its-own-directory

About Chintan Panchal

I am web developer having 4+ year of experience of web development. I have worked on codeigniter, symfony, laravel and wordpress.

View all posts by Chintan Panchal →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.