Laravel - Relationships - Constraining Eager Loading Of Morph To Relationships
If you are eager loading a morphTo
relationship, Eloquent will run multiple queries to fetch each type of related model. You may add additional constraints to each of these queries using the MorphTo
relation's constrain
method:
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\MorphTo;
$comments = Comment::with(['commentable' => function (MorphTo $morphTo) {
$morphTo->constrain([
Post::class => function (Builder $query) {
$query->whereNull('hidden_at');
},
Video::class => function (Builder $query) {
$query->where('type', 'educational');
},
]);
}])->get();
In this example, Eloquent will only eager load posts that have not been hidden and videos have a type
value of "educational".