Laravel: Forgetting a relationship after processing

You may have retrieved a related record from the database to do some kind of computation on, but then not want to return it from the controller. Here’s how to do it.

You’ve retrieved the relationship of a model when fetching the Model from the database, if we take our previous example :

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

You’ve retrieved the comments at the same time (and they actually work now you’re retrieving the foreign id to the comments), you’ve then performed some computation on them, for example determining if the title should be in a different colour based on the comments, or you want to manipulate the data before output.

Then, you want to output the data in a table, or as JSON and you don’t want all those comments attached to the data.

This is where we use:

$post_titles_with_comments->unsetRelation('comments');

Quite a handy little (undocumented) feature or as I’ve later discovered you could use makeHidden()

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.