Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4: many to many (insertion)

I have these tables in DB:

[posts, cats (categories), posts_cats (pivote)]

the relation between posts table and cats is many to many

I declared the relation in the models classes:

//Post.php
public function cats()
{
    return $this->belongsToMany('cats');
}



//Cats.php
public function post()
{
    return $this->belongsToMany('posts');
}

the question is, How to insert new post with multiple categories?

thanks,

like image 685
mwafi Avatar asked May 28 '14 09:05

mwafi


1 Answers

Let's say you know the id of the post then you can attach a single cat like this:

Post::find($post_id)->cats()->attach($cat_id);

Or attach multiple cats like this:

$cat_ids = array(1,2,3,4);
Post::find($post_id)->cats()->attach($cat_ids);

If you got the Post model object in a variable, lets say $post:

$post->cats()->attach($cat_id);

// Or with multiple
$cat_ids = array(1,2,3,4);
$post->cats()->attach($cat_ids);

If you have a single category as an model object in, lets say $model:

$post->cats()->save($model);

Watch out with @Gadoma's answer. Its not wrong, but if you want to add categories to an post that already has categories then you should use attach() instead of sync(). Sync() will delete all others that are not provided to it when used.

edit:
So if you are creating a new Post then you probably are doing something like this:

$post = new Post;
$post->title = 'The title';
$post->something_else = 'Lorem';
$post->save();

//So now you have both the model object (the $post variable) and the id ($post->id).

$post->cats()->attach($cat_ids);
like image 71
Ilyes512 Avatar answered Nov 13 '22 05:11

Ilyes512