7 months ago

Accessing nested many to many relation

Posted 7 months ago by bufferoverflow

I'm trying to access a nested many to many relation in order to send some notifications. But my code is so ugly and I think I can improve it a lot and also make it more performant.

$clients = [];
$models = $period->models;

foreach ($models as $model) {
    foreach ($model->clients as $client) {
        if (!in_array($client->id, $clients)) {

            // send email
            $client->notify(new \App\Notifications\PeriodNotification());

            $clients[] = $client->id;

I can not use hasManyThrough but since model->clients is a many to many.

Any ideas how to access those clients directly or just flatten that nested foreach?


Please sign in or create an account to participate in this conversation.