user2840318
user2840318

Reputation: 1127

Laravel: Many to Many, how to insert data?

I've got for the first time in L4 the need to establish a many-to-many relationship. For what I understood, so far, I need three tables... I have the following:

users
- id
- username
- ...

platforms
- id
- title
- ...

users_platforms
- platform_id
- user_id

How can I now insert data into the users_platforms table? I have the User model and the Platform model. How should both these be related... and how the actual content is saved to the related table?

On hasMany relationships I would create a new user and then save it like $user->something()->save($something) but I naturally can't do something like that in here.

Thoughts?

Upvotes: 0

Views: 260

Answers (1)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

Having a User model with your relation:

class User extends Eloquent {

    public function platforms()
    {
        return $this->belongsToMany('Platform', 'users_platforms');
    }

}

You just have to attach it:

$platform = new Platform;
$platform->name = 'OSX';
$platform->save();

$user = User::find(1);

$user->platforms()->attach($platform->id);

Upvotes: 2

Related Questions