Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 462
Robert Tillman Avatar asked Aug 04 '20 01:08

Robert Tillman


1 Answers

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');
    }
});
like image 123
linktoahref Avatar answered Oct 19 '22 10:10

linktoahref