Mahmoud Nassar Mahmoud Nassar - 1 year ago 76
PHP Question

Getting error when trying to insert a record that has composite primary keys

I have a Many-to-Many relation, so the implementation require to create new table with two primary keys ,,

here's the new table :

public function up()

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

but when try to insert data using this function :
//Insert new FriendShip into DataBase

public function InsertFriendShip($User1Id, $User2Id, $State)
$friend = new FriendShip();

$friend->User1_Id = $User1Id;
$friend->User2_Id = $User2Id;
$friend->State = $State;

// save new FriendShip to the database
return 'created';

ok it create the new record in database but although it return this Error
PDO::lastInsertId() expects parameter 1 to be string, array given

Answer Source

From what I can deduce, you have a Friendship Eloquent Model attached to the friendship pivot table. The problem with that is that Eloquent doesn't work with composite primary keys, so there's no real way of doing that.

You should have a look at the Laravel Eloquent Docs to see how to implement many-to-many relationships. In you case you could have a User model that looks something like this:

class User extends Eloquent {

    public function friends()
        return $this->belongsToMany('User', 'friendship', 'user1_id', 'user2_id');

    public function addFriend(User $user)

    public function removeFriend(User $user)


You can then add or remove a friend for any user very easily:

$user1 = User::find($id1);
$user2 = User::find($id2);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download