In this episode, we get hands-on and build the API endpoint for our posts feature—the backbone for showing posts on the timeline.
We start by creating the Post model and its migration so we have a database structure for our posts (just a simple body
field for now). After that, we generate a factory for our posts, which lets us easily make some sample data. Using Laravel's Faker, we set it up to spit out dummy sentences for each post.
Next, we actually use that factory in Tinker to quickly fill the database with 20 fake posts. With a bunch of posts in there, it's time to set up the backend so our app can fetch them. We create a controller (PostIndexController) and register a route (/api/posts
) in our API routes. Inside the controller, we add an __invoke
method to get all the posts ordered by latest.
To check it all works, we hit the /api/posts
endpoint and see our data show up. But one problem: we don't want all the posts at once, so we move to paginating the results (10 per page for now). Laravel automatically includes pagination info for us!
Lastly, we note that the current approach isn't perfect—we'll want to switch to cursor pagination soon. But for now, we've got a working endpoint and a foundation to build on as we tie this in to the client and tackle issues like loading more posts.