Xerakon
55
19
Laravel

Relationship Issues

Posted 2 months ago by Xerakon

Hey guys,

Having issues with referencing values through what I believe is relationship issues.

What I am trying to do is set up so that I can view the amount of patients that a doctor has, if they belong to the logged-in user. Right now, I can't even access the doctors that are connected to the user. I am using LaraTrust if that helps any.

From an administrator perspective, I can view everything just fine through the Doctor model. But the code I've been using authenticates users through the User model and down into the various tables to gather data. I'm not sure of a better way to do this.

For this particular piece, I'm not interested in listing out practices at all. Just any doctor that belongs to a practice associated with the logged-in user.

Schema: USERS table has a many-many relationship with a PRACTICES table. PRACTICES can have many DOCTORS, but DOCTOR can only have one PRACTICE. DOCTORS have many-many relationship with patients.

DashboardController.php

public function index()
{
    if (Auth::user()->hasRole('administrator')) {
        $doctors = Doctor::orderBy('full_name', 'asc')->paginate(10);
        return view('dashboard')->withDoctors($doctors);
    } elseif (Auth::user()->hasRole('representative')) {
        $doctors = User::find(Auth::user()->id)->practices()->doctors->orderBy('name', 'asc')->paginate(10);
        return view('dashboard')->withDoctors($doctors);
    } else {
        return view('dashboard');
    }
}

dashboard.blade.php

@role('administrator')
    @foreach ($doctors as $doctor)
        <tr>
            <th scope="row"><a href="{{route('doctors.show', $doctor->id)}}">{{$doctor->full_name}}</a></th>
            <td>{{$doctor->patients->count()}}</td>
            <td>#</td>
            <td>{{$doctor->created_at}}</td>
        </tr>
    @endforeach
@endrole
@role('representative')
    @foreach ($doctors as $doctor)
        <tr>
            <th scope="row"><a href="{{route('doctors.show', $doctor->id)}}">{{$doctor->name}}</a></th>
            <td>#</td>
            <td>#</td>
            <td>{{$doctor->created_at}}</td>
        </tr>
    @endforeach
@endrole

This is the error I receive: Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsToMany::doctors()

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

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.