Skip to content
Advertisement

Laravel API – Showing individual file through o2m relationship

So I have two models User and File, these are connected with a one-to-many relationship.

I have sorted the API routes and controllers to index all users, show specific user and index all files uploaded by that specific user. I do not know how to write the logic that will allow this route 127.0.0.1:8001/api/2/files/1 to show the first file uploaded by the 2nd user. So/2(seconduser)/files(shows all)/1(shows only 1 file)

This is my API code:

JavaScript

Files Controller

JavaScript

Users Controller

JavaScript

Advertisement

Answer

So here’s what a typical route declaration would look like. Note the user ID is not relevant to the file request, so the files endpoint is made separate from the users endpoint.

JavaScript

And then in your controller methods, you’re simply returning a list or a single item, mostly as in your original code. Note if you’re returning API data, you should explicitly return JSON.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement