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

SPL3S's avatar
Level 1

API routes to return json from controllers that return view

It might sound silly, but I never had interaction with API stuff until now. I need to prepare API routes for the app, I tried using the middleware group for the API header to return JSON of the model, but it always returns the whole HTML view.

I just copy/pasted web.php to api.php routes.

My question is if there is a way to get a JSON from a model when the return is view?

my current controller

    public function index() {
        $products = Product::paginate(30);
        
        return view('products.products', compact('products'));

    }

or do I have to create a separate controller for all API routes that will be called like this and middleware group passes as JSON?

    public function index() {
        $products = Product::paginate(30);
        
        return  $products;

    }
0 likes
3 replies
martinbean's avatar
Level 80

@spl3s I don’t really understand your question. If you want JSON returned from a controller, then you have to return JSON or something JSON-able. If you return a view then yes, a HTML view is going to be returned and not JSON.

SPL3S's avatar
Level 1

@martinbean yeah, after posting the question I realised it's a stupid question. I guess I have to create a controller for API routes that will return JSON, or is it better to make an if statement with expectsJson() in the current controllers?

martinbean's avatar

@SPL3S Personally, if I’m building an API then I’ll create separate controllers. That way my API isn’t tied to web routes, or querying the database for superfluous data, i.e. data for UI elements like navigation menus, select inputs in forms, etc.

1 like

Please or to participate in this conversation.