Support the ongoing development of Laravel.io →
Views Blade Architecture

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:

Business Logic

function getPosts() {
    return Post::all();
}

API Controller

function index() {
    return $this->businessLogic->getPosts();
}

Controller

(version 1, returns a view that includes the FrontEnd Framework to make an API call)

function index() {
    view('posts.index');
}

Controller

(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:

  • API Controller
  • Controller that serves an empty View for JavaScript
  • Controller that uses server side rendering

But then the problem is that I would have to do conditional routing depending on the client's possibility of rendering JavaScript...

Any ideas?

Last updated 3 years ago.
0

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.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

johannesz johannesz Joined 24 Feb 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.