Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

robot98's avatar

Having laravel as an API while still serving views in the browser

I'm doing a small project to learn Laravel (I'm new to it). The main part of the app is the api, as I'd like to be able to implement it anywhere I want. But I also want the same app to be accessible from normal browser, without doig it as SPA (I'm not using Vue). The frontend already utilizes the API via ajax in most of the parts, but things such as disallowing access to certain routes are handled by Laravel on the session-driven side (I still have normal logging in with sessions, but I want to totally scrap it and make logging in entirely by API). Now, I can see a few approaches: keep the frontend side as it is, with sessions, while keeping the same functionality in the API. This would be okay, but introduces a few problems: I would need to basically do everything twice, as I don't want to consume my own API in the controllers. Another approach is to only use one controller, but check if it's accessed by API or normal user (wantsJson()), but I'm not sure if this approach would be good. The last approach would be to keep everything in the API, set the default auth driver to use api tokens, and treat normal browser users as API too (I would need to pass the API token as a cookie to do this automatically). This would require CSRF protection as it's still a cookie, and also doesn't overally seem like a good idea. What I want is just to serve the basic view templates to the user via Laravel (and return errors if a user should have no access) while doing all the work in the frontend (js) via api. I don't really want to control the routes with JS, and I don't want my app to be entirely single page, but to handle the content on every page with js.

0 likes
1 reply

Please or to participate in this conversation.