I'm beginner in laravel. I created a form with title, body and tag input and there are 3 tables: posts, tags and post_tag.
Now I use this function to add new tags and attach them to the post
postcontroller.php
public function store(Request $request)
{
$input = $request->all(); //get inputs value
$tag = $input['tag'];
$tagdone = Tag::create(['name'=>$tag]);
$tagid = $tagdone->id; //insert tag to tags table
$posts = Posts::create($input); //insert posts table
$postid = $posts->id;
Posts::find($postid)->tags()->attach($tagid); //attach tag to the post
}
Actually 3 action in same time. But I think there are better ways than this one, so I'd like some feedback on what I've written.
public function store(Request $request)
{
$post = Posts::create($request); //insert posts table
$post->tags()->attach(['name' => $request->input('tag')); //attach tag to the post
}
@sid405 but I didnt insert any tags on tag table before and I want to insert tag and attach it to post in same time
on the other hand
$request->input('tag') is name of a tag and query want to insert tag name instead of tag id
your query show this error :
insert into posts_tag (created_at, posts_id, tag_id, updated_at) values (2015-09-19 08:09:38, 35, tagname, 2015-09-19 08:09:38))'
You have to create the relation in Post model like this
public function tags()
{
return $this->belongsToMany('App\Tag')->withTimestamps();
}
Now you can call as @sid405 suggested to save the tag on post model relation
public function store(Request $request)
{
$input = $request->all(); //get inputs value
$tag = Tag::create(['name'=> $input['tag'] ]);
$posts = Posts::create($input); //insert posts table
$posts->tags()->attach($tag->id); //attach tag to the post
}
Just a side note model name should be singular Posts should be Post