Eloquent Relationship Questions

Published 5 days ago by Xerakon

I'm trying to determine the best way to set this up, as my database schema is very heavily involved with many-to-many relationships.

Currently, it looks something like this:

users <---> practices <---> doctors <---> patients <---> orders <---> medications

Every relationship is many/many, EXCEPT that practices can have many doctors where doctors can only have one practice.

I've got so far using the documentation and tutorials down to the doctors table, and now I'm trying to determine how it might be possible to display the user's name next to the doctor they represent.

For this example, there is the users, practices, practice_user, and doctors table. Doctors table has the foreign key of practice_id to reference practices.

DoctorController.php

$doctor = Doctor::findOrFail($id);
$practice_id = $doctor->practice_id;
$practice = Practice::find($practice_id);
return view ('doctors.show')->withDoctor($doctor)->withPractice($practice);

doctors/show.blade.php

Doctor: {{$doctor->name}}
Practice: {{$practice->name}}
Representative: ???

Using the controller info, I can pull up the doctor and associated practice by passing through the foreign key id into the practice table. But I can't determine how I need to pass this up to determine the user.

Thanks!

Xerakon

On doctors/show.blade.php, I was able to pull up the User's name with this foreach loop:

@foreach($practice->users as $user)
    {{$user->name}}
@endforeach

But I feel as if I should be able to accomplish this without needing a loop.

Cronix
Cronix
5 days ago (727,800 XP)

Well, users is an array of many users, so you'd have to loop over it to get each individual user object. If you just want something like a comma separated list of user names, there are collection methods that could help with that.

{{ $practice->users->implode('name', ', '); }}
tykus
tykus
5 days ago (657,630 XP)

Can you describe what exactly you are trying to display?

Xerakon

I have a users table that has a many-many relationship with a practices table, connected via an id pivot table called practice_user. The practices table hasMany relationship to a doctors table, which belongsTo the practices table. What I'm trying to do, on the doctor's show blade/Controller, is display the Doctor's Name, the Practice's Name that the doctor belongs to, and the User's name that is tied to/represents the Practice that the doctor belongs to.

tykus
tykus
5 days ago (657,630 XP)

...the User's name that is tied to/represents the Practice...

Just one user??

Snapey
Snapey
5 days ago (993,535 XP)

I have a users table that has a many-many relationship with a practices table, connected via an id pivot table called practice_user.

So how do you hope to get the practice user? There can be many, as you have described

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