api route group or should they stay in the
web route group?
First, I recognize AJAX is a somewhat dated term, and technically we’re referring to an XHR (XMLHttpRequest), but I’m going to stick with it because I think it’s still a common way to ask this question. It’s sort of like TLS vs SSL. We all know one is more accurate, but sometimes language habits die hard. With that nerd sniping out of the way, on to the answer…
Personally, I would recommend that these calls be placed in the
web route group, even though they are being called in a very similar way to a traditional API. To understand my reasoning, it’s important to remember what is actually different between the
api route groups. In a default Laravel install, the only real difference between the
web group and the
api group is which middleware are applied, and that the
api group has a path prefix and a rate limiter. That’s really it. There isn’t anything more special about it. You can open up
Http\Kernel.php to confirm this.
web route group, and not put it in the
api route group.
Also, and this is a bit more subjective, but explicitly calling something an API, makes it seem like you should adhere to a spec. You should care about breaking backwards compatibility. Even if you don’t officially have any external API callers, and you control anything that should be calling the API, it still feels a bit chaotic to me to label something an API and then change it with no careful planning. On the other hand, if it’s just one of your web controllers, I don’t think there’s any implicit contract expectation.
One nuance I would add is if you’re using Sanctum. In this case, I would instead argue that these controllers should be placed in the
api route group. That being said, you likely aren’t using Sanctum if your app is only rendering Blade views for users to point and click.
Finally, I want to make the point that just because we’re keeping these AJAX controller in the
web group, that does not mean we should jam them into other existing controllers. More often than not, these types of controllers will be invokable controllers with just a single method in them. It keeps your controllers uniform, following the resource conventions, and preventing them from growing to 1000-line monsters.