I am trying to use many-to-many relationships between my posts and categories models. So far I created posts , categories and post_categories tables.
In my models, I have my relationships
class Post extends Eloquent {
public function categories()
{
return $this->belongsToMany('Category', 'post_categories','category_id');
}
}
class Category extends Eloquent {
public function posts()
{
return $this->belongsToMany('Post','post_categories');
}
}
and in my controllers when I try to create a Post instance by :
$post = new Post;
$post->title = e(Input::get('title'));
$post->slug = e(Str::slug(Input::get('title')));
$post->content = e(Input::get('content'));
// Was the blog post created?
if($post->save())
{
$id = (int) Input::get('category_id');
$category = Category::find($id);
$post->categories()->attach($category);
// Redirect to the new blog post page
return Redirect::to("admin/blogs/$post->id/edit")->with('success', Lang::get('admin/blogs/message.create.success'));
}
After submitting form , I can see blog post is created normally. When I check the db , Category_id is inserted inside post_categories table but post_id is always 0.
Can anyone help me to fix this?