Francisunoxx Francisunoxx - 3 months ago 13x
PHP Question

How to create two Foreign Key on pivot table linked to one Primary Key

I'm trying to implement where I need to insert or save the current user that logged in. Inserting the recipient into user_id column works well but I need to manipulate who send the data I need to get the user id. I have two tables users and documents with a pivot table document_user.

users table

Schema::create('users', function (Blueprint $table) {

documents table

Schema::create('documents', function (Blueprint $table) {

document_user - pivot table

Schema::create('document_user',function (Blueprint $table)


DB Design:


Note! I only insert few column in my users table migration just to save a line of text.



public function documents()
return $this->belongsToMany('App\Models\Document', 'document_user', 'user_id', 'document_id');


public function recipients()
return $this->belongsToMany('App\Models\User', 'document_user', 'document_id', 'user_id');

Inserting records based on the user's choice to pivot table works well. But when I try to rollback my migration and alter my pivot table to this.


I get a error it says:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`webdev`.`document_user`, CONSTRAINT `document_user_sender_id_foreign` FOREIGN KEY (`sender_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) (SQL: insert into `document_user` (`document_id`, `user_id`) values (34, 10))

How can I achieve inserting the current user in my pivot table? So I can track who sends and receive the data. Any help would appreciated! Cheers!


Don't use a pivot table! Your better off adding a user_id column to your documents table. Make sure you have the correct eloquent relationships as well, that can cause errors.

Hope this helps!


You wrote thaf you get the error as soon as you add this to your table:


It could be because your creating two rows called ┬┤sender_id┬┤. I hope that works!

Edit 2:

I looked around a bit online, and found this post on laracasts: Also, this error is normally thrown when your trying to get a null value from another table and put it into a row that isn't nullable.