In this lesson, learn to load related data or subresources for a primary record.
Now that we've seen how to build a basic API in Laravel, let's see how to load in subresources. What's a subresource? In our case, a subresource is going to be a way to get the questions related to a poll. We want to build an endpoint at polls, forward slash, poll ID, forward slash questions, to return the questions associated with the poll. We'll begin like we always do with the first step of building a route. So, we'll open the routes file at routes api.php and we can add under line 26 route, colon colon, get, and we are going to access polls, forward slash and then in curly braces poll and then questions.
This will be talking to the polls controller and the method it will call will be questions. Now to build our corresponding function in the polls controller, we'll open up app, http, controllers, polls controller.php. All the way on the bottom, we'll add a new function called public function questions. This function is going to take two parameters. The first, of course, is going to be our request, the second will be a poll instance.
So we have a poll and we have a request. Now how do we get the questions for our poll? That's actually pretty easy. We can call questions, is going to be equal to poll, arrow, questions. If you've used Laravel in the past, you know that the poll model has access to the ability to get this subresources, in this case, our questions. Now on line 60, add return, response, arrow, json, and we'll return our questions and a 200.
And now we can open up Insomnia, and we'll want to edit our get single poll and we'll add questions to the end of our URL. We'll send this request, and we'll get nothing, actually. Now, why is that? If you know Laravel, you should know the answer at this point. We didn't yet define any relationships in our Laravel model. So let's go back to our code editor and we'll open up our poll class in app, poll.php, and we need to add a new relationship for our questions model.
So we'll add a new function, that's public function, questions, and then here we'll have it return, this, arrow, has many, app, backslash, question. Save this. Let's go back to Insomnia and try it out one more time. And there, we get all of our questions, notice with our poll ID is equal to 4. So now we built out an API to be able to get subresources off of that API.
We can talk to a poll and get the questions related to that poll.
- Reviewing the basics of an API
- Basic pieces of the Laravel framework
- Reading, adding, editing, and deleting a record
- API errors and exceptions
- Transforming your API data
- Returning nested and sideloaded data
- Creating a logging middleware
- Authenticating to your API
- Basic and advanced endpoint testing