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

nmp4817's avatar

Laravel API Resource

Hi!

Does Laravel API Resource have to be based on the Eloquent Model? Or can it be unrelated?

Let's say I have navbar endpoints that return data from few different models

can I create NavbarResource? Or what would you suggest?

New in town still trying to learn things! Thanks

0 likes
6 replies
tykus's avatar

First question: are you building an API or a classic server-rendered PHP application?

1 like
nmp4817's avatar

Thanks for responding super fast.

Rest API application

tykus's avatar

Ok.

In theory, you could use an API Resource to represent the Navbar, since the Resource itself could be anything (e.g. an array), but then what do you gain - you are effectively passing an Array to the Resource, when returns an Array (from toArray method).

How do you intend to pass the Resource down the pipe (as a response)?

1 like
nmp4817's avatar

Correct! Will be passing an array to Resource. And then was planning to put some checks inside Resource like if a user has an admin role add or hide particular attribute. Not sure it is the correct way of doing it. What do you suggest?

Thinking more about it. Resource would be only useful in case there is a collection to pass to a Resource?

The Resource will be the API response (JSON).

tykus's avatar

I don't see how the Response class would really benefit you. You could do all of that in your own class; maybe even consider implementing the Responsable interface (if relevant). This will allow you to keep all of the logic associated with the navbar together. Check out this blog post for some context - that will not always be directly applicable, but should provide some insights.

1 like
nmp4817's avatar

thanks for sharing and explaining. I will see what will be the best thing to use.

Please or to participate in this conversation.