Lovelock
Lovelock

Reputation: 8075

Laravel 4 - Inserting multiple values into a pivot table

I have a users table and also an accounts table.

This accounts table defines which accounts a user can have.

e.g.

accounts:

id| name

1 | library
2 | school
3 | maths

users:

id| username

1 | username1
2 | username2

I now have another table: users_accounts

user_id | account_id

I am making an interface for new users to be created. On this page I have basic details but also a list of checkboxes (created from the accounts table). The checkboxes represent what account a user needs to have set up for them.

What I want to do is when creating the account:

$user = User::create($input);

I want to also add the user id and the accounts they need setting up into the users_accounts table. A single user can have multiple accounts required.

Can I do this using a pivot table and belongsToMany?

In long terms:

$user = User::create($input);

loop through the checkboxes {
    add a new row into the user_accounts table with the ticked checkboxes
}

Upvotes: 1

Views: 231

Answers (1)

mopo922
mopo922

Reputation: 6381

You're almost there!

$user = User::create($input);

$userAccounts = array();
foreach ($checkboxes as $accountId) {
    $userAccounts[] = new UserAccount(['account_id' => $accountId]);
}
$user->accounts()->saveMany($userAccounts);

Doc: http://laravel.com/docs/5.0/eloquent#inserting-related-models

Upvotes: 1

Related Questions