I'm attempting to eager load a user's notifications with a relation that depends on a value of notification model:
$notifications = $user->notifications()
->with([
'notifiable' => function ($query) {
// Only load notifiable relation if notification 'notifiable_type' equals...
},
'notifiable.group:id,title' => function ($query) {
// Only load notifiable.group:id,title relation if notification 'notifiable_type' equals...
}
])
->get();
The issue is the $query
within the closures are querying on the notifiable
relation rather than the notification model itself... I'm obviously missing something very trivial. Any suggestions?
You could make use of Lazy Eager Loading
$notifications = $user->notifications;
$notifications->each(function ($item) {
if ($item->notifiable_type == 'value-one') {
$item->load('notifiable');
}
if ($item->notifiable_type == 'value-two') {
$item->load('notifiable.group:id,title');
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With