Laravel: Code in Controller or a separate Class?


The problem with a lot of online advice is that it’s not backed by extensive experience at all, rather picked from small experiments and guesses..

A common advice you’ll hear, especially in Laravel community goes like this: Controller’s should only contain HTTP/requests logic, everything else should be separated.

The issue with such statements is that it’s incomplete and misses the whole point!

The reality is, Controller are just Classes and will execute whatever you throw at it. You could put everything in a single or multiple Controllers and be just ‘okay’.

Contrary to placing all the logic in a single Controller.. if you separate it too early, without scoping the entire or partial app, you’ll end up overcomplicating your code.

So no matter which route you pick you’re asking for trouble!

In both scenarios you’re doing what a Junior does when they learn OOP the first time. They use it everywhere! the entire app could be setteled in a few basic functions but they decide to create a bunch of Classes without any reasoning.

Will separating logic into Classes help with testing and understanding the code better in a next couple months when the app is performing complex operations and it’s much larger? nop, none of that. They’re doing it just for sake of it.. Poor decision making..

It’s the same principle with logic in the Controllers, think carefully if you really need to separate it, should the queries go in the Models, and the other logic in separate service classes? if the answer is “I don’t know yet..”, then there’s no need to overenginner your app.

A lot of the time you’ll sense the need to separate the logic from Controller, you’ll get that feeling, that’s when you start moving things around. There’s nothing set in stone. Know your project and its scope!

It’s about a careful balance, what you really don’t want is create 10 classes when all you needed is 10 functions that could be placed in a single Controller, but you’ve separated them into classes and made hell for everyone else.

Do not over-engineer your small applications.


Leave a Reply

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