How to save a many to many record in Laravel 3?

193 Views Asked by At

When I am creating a snippet model I want to directly add a relational record to the intermediate table but I get this error:

Unhandled Exception

Message: Method [save] is not defined on the Query class.

When I execute this code:

$new_snippet = new Snippet(array('snippet' => Input::get('snippet'), 
                                   'title' => Input::get('title')) );

foreach (Input::get('categorie_ids') as $categorie_id) 
{
    $categorie = Categorie::find($categorie_id)->snippet()->save($new_snippet);
}

I'm relatively new to working with relational models in Laravel so all suggestions on how to do this are welcome.

1

There are 1 best solutions below

0
On

After checking the documentation again and trying out some stuff I came up with this solution:

$new_snippet = Snippet::create(array('snippet' => Input::get('snippet'), 'title' => Input::get('title')) );
            foreach (Input::get('categorie_ids') as $categorie_id) {
                $categorie = Categorie::find($categorie_id)->snippet()->attach($categorie_id, array('snippet_id' => $new_snippet->id));
            }

Basically I just used attach instead of save.