mardi 4 décembre 2018

Laravel Displaying Content via Eager Loading (Nested Structure 3+ Level) using Foreach Statement

I have got three models

  1. Contacts Model
  2. Contact Roles Model
  3. Project Model

Setup

  1. contacts can belong to multiple projects. (Many to Many)
  2. each project has its own contact roles created by user. (One to Many
    • Roles are specific to projects)
  3. Within selected project, a contact can be assigned to multiple roles (Many to many).

I am currently building my blade view files and have an issue with loading the data with foreach loop and an if statement.

Question 1:

            @foreach ($project->contacts as $contact)
                @foreach ($contact->contactrole as $role)
                    @if ($role->group == 'owner')
                    <li>  -  </li>
                    @endif
                @endforeach
            @endforeach

I have role groups that are predefined by my application, user chooses it when they are creating a new role. I display all "contacts" with given roles on a single page but separated categorically as above. I am able to accomplish that by above code in my view file. Issue is sometimes this "contact" person can have multiple roles in a different role category, since I iterate through their role, view file repeats the output as many as their roles. (5 different roles will give me 5 repeat of the same role, 5x5 = 25 on one page).

How can i modify my code is able to display multiple roles of that contact on the same page without repeats?

Question 2: I thought about moving the if statement outside of foreach statement something like @if ($project->contacts->contactrole->group == 'owner'), it fails, it says contactrole does not exist.

Question 3: It seems that I will more nested data to display? What would be the easy/proper way to display and be able to run if statements on data's conditions?

How I retrieve data in controller

$project = Project::with('contacts.contactrole','companies.companyrole')->findOrFail($projectid);



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2QbHZ4W
via IFTTT

Aucun commentaire:

Enregistrer un commentaire