I'm currently working on a project and ran into a problem regarding rendering. Basically, I want to create a REST API that's consumed by a FrontEnd Framework such as Vue.js, Angular, etc (or by an Android App later on...). I wanted to create a "fallback", though, where the site would work without JavaScript as well, for all the people that don't use JavaScript.
Let's assume:
function getPosts() {
return Post::all();
}
function index() {
return $this->businessLogic->getPosts();
}
(version 1, returns a view that includes the FrontEnd Framework to make an API call)
function index() {
view('posts.index');
}
(version 2)
function index() {
$posts = $this->businessLogic->getPosts();
view('posts.index', ["posts" => $posts]);
}
So the problem is quite obvious. Basically, Controller v1 returns an "empty" view that makes a FrontEnd API call to then render the page, while Controller v2 uses server side rendering without using any JavaScript. How do I resolve this? I could create yet another Controller, so I would have:
But then the problem is that I would have to do conditional routing depending on the client's possibility of rendering JavaScript...
Any ideas?
You may create controllers for both, users with js and without. Before routing you would create a Middleware to check if user has js. This is the easiest way in my opinion.
Depending on your controllers and what they return you could create a master Middleware controller. You create a controller as usual for all your modules. The controllers than only return the json data. Your master controller or a Middleware could hook the process between controller - frontend and decide either it's js or not. If I am not wrong Laravel fires events before rendering a view. So you could start there.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community