NXA
NXA

Reputation: 440

In Laravel, do I have to create a separate model and controller for each database table/collection?

I am developing a little application with PHP web framework Laravel v6 and MongoDB (with jenssegers moloquent) as database engine. This is my first encounter with any MVC framework. I have the following collections in my database:

  1. allPaintingsCollection
  2. paintingHistoriesCollection
  3. paintingCategoriesCollection
  4. artGalleriesCollection
  5. paintingArtistsCollection
  6. supervisorArtistsCollection
  7. smPlatformsCollection
  8. nonSmPlatformsCollection
  9. targetSchoolsCollection

I have been following this tutorial. I have the following two questions:

  1. Do I have to create a separate Model (separate class in a separate file) for each collection above?
  2. Do I have to create a separate Controller (separate class in a separate file) for each collection above?

Upvotes: 0

Views: 718

Answers (1)

Vinayak Sarawagi
Vinayak Sarawagi

Reputation: 1062

New Answer: 1. Yes, you will need to create a separate model to use the ORM. Ideally, the model should only support a single collection, doing so you can create custom logic. Remember, One Model One Collection/Table.

  1. For Controllers, you can write it any way you like, you can use all models inside a single controller. But what I have learned so far using Laravel, you should create a single controller for each model to fully and logically support the separation of concerns.

Know the BTS:

Laravel heavily uses PHP Composer's autoloader functionality, so having multiple classes in a single file won't work.

For example, when autoloader starts, it would look for User class in \App\Models\User.php file. Having multiple classes in a single file won't help in this case.

Latest Laravel's version follow PSR-4 standard. You can have a look at it for more understanding.

For more PHP coding standards you can have a look at PSR-2 standards.

Upvotes: 1

Related Questions