jiraiya jiraiya - 11 months ago 76
PHP Question

Arranging models and controllers in Laravel

I have an application pretty much nearing completion in Laravel which I just lately began using and I have to say, I am loving it.

My application works fine, my question relates to best practice and opinion really.

Say I have the following hypothetical simple set-up.

Route: Brand -> This page loads an index of shoes for this brand.

Controllers: BrandController, ShoeController

Models: Brand, Shoe

At present when someone goes to the brand route with an id, I am calling the ShoeController to load a view with a list of shoes for that brand.

Is this the correct way to organise things or should all code for the Brand route be encapsulated in the BrandController and just call the Shoe Model to return the results within the BrandController?

I hope this is clear enough as an example.

Answer Source

You're totally free to organize. But itsn't very nice to combine different subjects.

Let me give an example:

If you've a route, for example: /brand/overview/1, so you can call the shoe model from your brand controller for getting the shoes with brand_id 1.

On the view, you can link directly to a shoe route (shoe controller), for example: /shoe/details/5.

Generally, controllers are thin controllers. Their jobs are:

  • delegating tasks
  • consolidating data

So don't commingle CRUD (create / read / update / delete) methods for different entities.