Laravel: calling the View on the Routes vs Controller

  • I want to know what are the differences between using Routes and Controller? Is there a major difference in Laravel’s system, or is it just a matter of logic?
  • Is there a difference between calling the View on the Routes and the View on the Controller?
  • Does the Controller automatically cache the View and Routes does not? Because I read somewhere that if we call the View in the Controller, it will be cached, but if we call the View in the Routes, it is not so we have to cache the View manually in the Routes. Is this true?

Think of logic that goes in routes as one off simple functionality (aka lightweight) and the logic that goes into controllers is a bit more heavy which means you can often do a bit more. Controllers are typically full classes with several methods, the code you put in a route is usually a one off function (aka a closure).

As far as I know there is no real difference between calling a view in a route vs a controller, but I could be wrong. Ideally views can get big, require several variables and need some more setup logic before they can be shown. Which is why you often see them use controllers. However if you have something as simple as a redirect, you might just see the redirect in the route itself using a closure based setup.

As for caching, if you are looking to do route caching they advise you use controllers because closure based won’t work (https://laravel.com/docs/7.x/controllers#route-caching). However, they seem to remove this language in the 8.x version so perhaps someone else can confirm this is still the case.

In short, if you are doing something really simple without much logic and don’t need to cache a route, closure is fine. If you are doing something a bit more complex (or expect to in the future) you should go with a controller.

:slight_smile:

2 Likes

Thank you for answering my question.The answer was very complete.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.