Kareem Nour Emam
Kareem Nour Emam

Reputation: 1054

Foreach loop inside laravel controller

I have recusrive function that build tree form my categories list i finished it and it working fine, but i have 2 approach to put it inside helper function and call it in blade, or to create class and call it in my controller then controller pase it to view.

So my question, is the second approach wrong (to do foreach inside the controller)?

Upvotes: 1

Views: 1076

Answers (2)

Shobi
Shobi

Reputation: 11511

From the principles of MVC architecture.

The responsibility of the view is to deal with presentation logic. In context of web the goal for view is to produce a response to the user(link)

So all your logic of generating data should be residing inside the controller. Then the controller should pass that data to the appropriate view. The view should only be responsible for presenting the data to the user.

Edit

suppose you want to print a list of menu items from an array then you can do that from blade. But if you are calling a function to get the array and do some sorting/filtering on that array then doing some checks to make sure array is a valid one etc... then it just bloats the view. so these kind of logic can be put in controllers. I hope you got the point

Upvotes: 1

Harsh Wardhan Gaur
Harsh Wardhan Gaur

Reputation: 56

If I have to do the task I will each and every calulation in the controller itself than only will pass it to the view.

View must be used to view the data and not to do the looping and other operations.

Upvotes: 1

Related Questions