Ryuzakiss
7 months ago

Laravel 5.4 - Creating new Model and attach data to PIVOT

Posted 7 months ago by Ryuzakiss

Hello,

I need help on something that I can't figure out.

So basically, I have a Model named Group AND User :

groups_table

id,
name,
slug,
user_id

users_table

id,
name,
email,

On the Group Controller I have this method:

public function save(Request $request)
{
 $model = new Group();
 $model->addGroup($request);
}

And on my Group model:

public function members()
{
    return $this->belongsToMany(User::class, 'group_user');
}

public function addGroup(Request $request){
 $user = $request->input('members');

$values = [
        'name' => strtolower($request->input('group_name')),
        'slug'=> str_slug(strtolower($request->input('group_name'))),
        'user_id'=> auth()->id(),
    ];

    $this->create($values);
    $this->members()->attach($users); // Add all the selected users to the newly created Group
    return $this;

}

When sending the datas, well it create the new model but the attach method fails.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'group_id' cannot be null (SQL: insert into group_user (group_id, user_id) values (, 2), (, 1))

It seems the attach method doesn't get the id of the created model.

Please sign in or create an account to participate in this conversation.