Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mohammad6006's avatar

insert and attach tag to the post in same time

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.

0 likes
5 replies
sid405's avatar

@mohammad6006

public function store(Request $request)
    {
        $post = Posts::create($request); //insert posts table
        $post->tags()->attach(['name' => $request->input('tag')); //attach tag to the post
    }

It won't get any shorter than that

mohammad6006's avatar

@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))'

tagname should be tag_id

saqueib's avatar

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

sid405's avatar

@mohammad6006 @saqueib I don't understand why sometimes coders will use

 $input = $request->all(); //get inputs value

and create useless variables for php to deal with instead of just using

 $request->input('some_variable'); //get inputs value

Is it habit from the L4 days?

Just a friendly question :)

1 like
sid405's avatar

@mohammad6006 if you get an error we need to see the model as you may not have set the relationship correctly.

The code i wrote does exactly what you'd expect it to :)

Please or to participate in this conversation.