Eager Loading Polymorphic Relationships

Feb 03, 2024

In case you're retrieving a huge data, it's so IMPORTANT to indicate which columns exactly you need. For instance, if you want to get the phone details with its creator, you should use Eager Loading and select the columns ONLY that you need for more optimization:

 

Phone::with(['user:name'])->get();

 

The previous code will throw an exception because Laravel, when joining both tables, will not find the `user_id` so, we should get both the `id` and `name` columns. But, what if you wanna retrieve data with Polymorphic Relationships?

 

You can say that you will do the same thing:

 

Phone::with(['image:imageable_id,name'])->get();

 

The former code will throw an exception, also, that's because Laravel needs the `imageable_type` column to match its value with the proper model class

 

We can that It does not matter the columns you select whenever you get the columns that are required in the join operations.

AI Assistant

Summarize, simplify, and ask questions about this content using your preferred AI provider.

Text Tools

Generate cleaner and easier-to-read versions of this content instantly

Have a Question?

Ask anything related to this content and get a focused AI-generated answer.

0/500
Mahmoud Ramadan
Author

Mahmoud Ramadan

Mahmoud is the creator of Digging Code and a contributor to Laravel since 2020.