Jonathan Reininck wrote a cool article on how you can create dynamic releationships. This technique will keep the number of queries and the memory used to a minimum.

I hope that gives you a good overview of how you can use subqueries to create dynamic relationships in Laravel. This is a powerful technique that allows you to push more work into the database layer of your app. This can have a huge impact on performance by allowing you to drastically reduce the number of database queries executed and overall memory used.

https://reinink.ca/articles/dynamic-relationships-in-laravel-using-subqueries#dynamic-relationships-via-subqueries