In this episode, we focus on pulling out and displaying relational data in Laravel. We start by looking at a user’s posts and see how to access this relationship in code. First up, we check out how Laravel returns related data as a collection, which can be looped over using a simple foreach
loop—just like plain PHP.
We then move into practical territory: setting up a route and view to list a user's posts, passing just the posts (or user if needed) to the view, and using Blade's loop syntax to display each post's ID and body. We see the real output in the browser, and even discuss ordering the posts, trying it out both in PHP (with slower results) and, more efficiently, directly when building the query with Eloquent’s orderBy
or the handy latest()
shortcut.
Throughout, we clarify the difference between methods run on collections (in code, after data is retrieved) and at the database level (while fetching data; way faster for big data sets). We also touch on getting just the first record, how to count results, and how to output a grammatically correct post count (using Laravel’s pluralization helper for “post” vs. “posts”).
After this episode, you should be much more comfortable pulling relationship data from Eloquent, outputting it in views, handling ordering/sorting, and showing nice summary lines—just like you see on real web apps every day.