Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Blackpig's avatar

Many to Many Pivot table column names

Hopefully a fairly simple issue and I'm just missing the bleeding obvious.

I have 2 models Clients and Bookings that are Many to Many related via the client_booking pivot table.

My Clients model relationship to bookings is set up as follows:

public function bookings()
    {
        return $this->belongsToMany('Modules\Courses\Entities\Booking', 'courses__booking_client');
    }

and my Bookings model relationship to Clients is set up as follows:

 public function clients()
    {
        return $this->belongsToMany("Modules\Client\Entities\Clients", "courses__booking_client");
    }

My courses__booking_client table just consists of two columns booking_id and client_id

In my controller I can add multiple clients to a booking in the store action, I loop through save the new clients and then attach them to the newly saved booking:

// pseudo code below 
// loop through and create the clients using populated data from form
foreach ($request->clients as $newClient {
    // aggegate the data into an array

    $client = Client::create($data);

    $clientIds[] = $client->id;
}

// create the booking
$booking = Booking::create($bookingData);

// Now associate the clients to the booking
$booking->clients()->attach($clientIds); <-- Uh oh!

Everything works until the uh oh line - clients are created, booking is created but I get an exception thrown:

Column not found: 1054 Unknown column 'clients_id' in 'field list' (SQL: insert into `courses__booking_client` (`booking_id`, `clients_id`) values (9, 21), (9, 22), (9, 8))

Why is eloquent trying to populate a column clients_id instead of client_id. All the docs use singular for the column name. e.g user_id and role_id even though the model relationships are plural https://laravel.com/docs/5.4/eloquent-relationships#many-to-many

And how do i go about rectifying this - is this a bug or do I need to rename my table column to match?

TIA BP

0 likes
1 reply
Blackpig's avatar

There you go,

I'm missing the bleeding obvious - bit of rubber duck as I read my question back.

My Clients model is plural and thus the pivot table column name is also. Doh!

Move along, nothing to see here.

Please or to participate in this conversation.