Skip to content
Advertisement

Laravel Load Relation With Condition On Model

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?

Advertisement

Answer

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');
    }
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement