Ad

How To Eager Load And Query A Pivot Table Using Eloquent - Laravel 5

- 1 answer

Situation: A single appointment can be related to many clients and many users, so I have a many-to-many relationship (pivot table) between appointment and client, and another between appointment and user

I'm trying to write the eloquent query to get a client's information, with all its related appointments and the users related to each of those appointments.

Tables

|appointment| 
|           |     
-------------
| id        | 
| time      | 
| created_at|
| updated_at| 


| client    |  | appointment_client |
|           |  | (pivot table)      |
-------------  ----------------------
| id        |  | appointment_id     |
| name      |  | client_id          |
| created_at|  | created_at         |
| updated_at|  | updated_at         |   


| user      |  | appointment_user   |
|           |  | (pivot table)      |
-------------  ----------------------
| id        |  | appointment_id     |
| name      |  | user_id            |
| created_at|  | created_at         |
| updated_at|  | updated_at         |

Appointment.php model

public function client()
{
    return $this->belongsToMany('App\Client')->withTimestamps();
}

public function user()
{
    return $this->belongsToMany('App\User')->withTimestamps();
}

Client.php model

public function appointment()
{
    return $this->belongsToMany('App\Appointment')->withTimestamps();
}

User.php model

public function appointment()
{
    return $this->belongsToMany('App\Appointment')->withTimestamps();
}

On the client/id show page, I would like to show the client's information, list all of the appointments related to this client, and get the related user information for each appointment.

Not sure how to get the users related to the appointments with that:

    $client = Client::with('appointment')
            ->where('id', '=', $id)
            ->firstOrFail();
Ad

Answer

It should be enough to just do:

$client = Client::with('appointment', 'appointment.user')->findOrFail($id);

This will load the client with given ID, then eager load their appointments and then, for each of the appointments, it will load related users.

Ad
source: stackoverflow.com
Ad