Laravel relationships and pivot tables

Tags: , ,



I’m working on my first ever laravel app, now I’m at the stage of creating some relationships for my content types.

In the app I can create an appointment which in the process of doing so also saves the details and creates a new client. However I want my user to be able to see the their clients “history” and see all appointments they’ve booked.

So far I’ve added hasMany relationship to my client model and the inverse hasOne in the appointment model. Therefore my thinking so far is that a client can have many appointments but an appointment can have only one client.

However…

I’m really struggling with connecting both together as ideally I need to do something like this:-

For X client id get all appointments that match client id

In this context is this where would you use a pivot table to manage this? If so where do you place the logic to handle the attaching/deattaching of IDs in the model(s)?

Or is there something I’m missing from my call as my appointment function in my client model only has the following: –

       return $this->hasMany('AppAppointment');

Do I need to pass anything else?

I’ve read the docs and I’m utterly clueless and coming from a WP background so any help at all would be fantastic!

Answer

Since you’re talking about a one-to-many relationship you don’t need a pivot table. Instead your appointments table should have a client_id column that links to the client.

To get all appointments for a client you just need to get the appointments property (assuming your relationship method is also called appointments():

$appointments = $client->appointments;

// OR

$appointments = AppClient::find($client_id)->appointments;

Since that property doesn’t exist on the class, Laravel will look for a relationship method with the same name. Once it found it Laravel will query the appointments table for entries with that client’s ID and return them in a Collection.

The relationship method also helps when storing a new appointment:

$client->appointments()->create(['date' => request('date'), ...]);

Here you don’t need to manually add the client_id to the appointment since Laravel knows about the relationship.

You have some flexibility in naming of your methods/table columns etc. but I usually find it best just to stick with the Laravel conventions.



Source: stackoverflow