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

rudolfbruder's avatar

Dynamic API endpoint

Hello there,

I am looking into building an API endpoint which would return Model resource with given columns that are being sent as url request parameter.

Thing is that this should also work for model's relationships columns - meaning that my endpoint could look somewhat like this:

localhost/api/books?columns=id,title,description,author.first_name,author.last_name,distributor.id

This endpoint would return only columns id,title,description of the book model and then author's first and last name and distributor's id only

Does anybody know somewhat best practice which could be applied in this problem? I am looking for a way of building the controller index method and using laravel resources for this however I am confused with the way how to build the logic itself.

Thank you.

0 likes
5 replies
tykus's avatar

Spatie has a package that somewhat handles this type of behaviour. It might not be exactly what you need; but source-diving will give you ideas about how you could implement your own

2 likes
webrobert's avatar

@rudolfbruder Take the parameters from the request to form a select. just be sure to filter against allowed columns.

rudolfbruder's avatar

@webrobert Yeah that was the way to go however once I started thinking about the recursive function to get the columns of relationship and it's relationship it got tricky.

Please or to participate in this conversation.