best way to retrive a collection from -many to many- connected to -one to many- relation (laravel7)

you can see a part of my database in the image below:

the goal of this design was to able the admins send alerts to users filtered by center and field(dynamically). if you think this is a bad design tell me (please say why and how should I improve my design).

enter image description here

now if I want to get the alerts for a user I should do this:

    $userAlerts = collect();

    auth()->user()->branch()->first()->groups()->get()->each(function ($item, $key) use ($userAlerts) {
        $item->alerts()->get()->each(function ($item, $key) use ($userAlerts) {

this code is ridiculous and I don’t want to do it in this way.

instead i want to do something like this:

    $alerts = auth()->user()->branch()->groups()->alerts() // i want this // method 1


    $alerts = auth()->user()->alerts() //or maybe this // method 2

can I do something like this without changing the database? (method 1 or 2).

Source: Laravel StackOverflow

Leave a Reply