Laravel: Retrieving columns from a model, and a relationship

I scratched my head over this for quite sometime today, but after a lot of digging I found a solution…

Let’s take for example the following code:

$post_titles_with_comments = Post::with('comments')->get(['title']);

I’m doing this because I want to retrieve all the post titles (and their comments), I’m being selective about what I fetch because I’m going to return this over an API as JSON.

This will indeed fetch the titles, but the comments relationship (a HasMany) will be empty!

I scratched my head for a bit on this, but I’ve worked it out, the key here is when you’re telling it what fields you want from the Post, you MUST include the key that the Comments would use to identify the Post they belong to, otherwise they cannot be found!

In most cases you’ll find this the id!

$post_titles_with_comments = Post::with('comments')->get(['id', 'title']);

I hope this helps someone!

One Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.