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

riomigal's avatar

Consume JSON Api with Laravel

Hello

How can I map Laravel model to a JSON Api?

E.g. I have two Laravel API:

The first is a JSON API Service from where I fetch posts.

The second is a Client which consumes the Posts. I understand that I can use json_decode, toJson to decode the posts to Array or Std Obj.

But my question is how can I map the results to a model, e.g. that I can use static methods like Posts::all()?

Thank you!

0 likes
4 replies
automica's avatar
automica
Best Answer
Level 54

@riomigal if you want to treat a 3rd party service as the equivalent of a model using a database, then you should look at using Repository Pattern and Eloquent Resources

You may find just querying the external api, and then using the various methods within Collections maybe simpler depending on your use case.

riomigal's avatar

Hi,

Thank you for the reply.

The article on medium.com is very interesting. Actually that's similar to what I am doing but I just use the model class instead of a resource and then inject it in the controller constructor. However is there the possibility to connect a model directly to a resource. Instead of using the DB Driver to use the models directly with the JSON API. Or am I complicating things? (Overthinking)

Best regards

automica's avatar

If you are using a repository, then that'd be a replacement for using a model within your controller. Theres little value connecting the repository to the model and then calling it via the model, as you get all the overhead of Model without needing the methods extending it gives you.

If, however, you need to relate the data you are getting from the external API, then it may be prudent to create a task to do daily imports and then stuff these records into a table. Then you can query this data locally using eloquent.

Please or to participate in this conversation.