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

joefly's avatar

Adding Tags to Posts in Store Method

I have a form with input fields for 'title' and 'body', and checkbox inputs for 'tags'. I'm trying to attach the tags to the post in the store method of the PostsController. At this point, I am able to collect the chosen tags into an array, but I'm not sure how to attach them to the post. Here is my store method:

    public function store()
    {
        $tags = [];
        if (!empty($_POST['tags'])) {
            foreach ($_POST['tags'] as $tag) {
                array_push($tags, $tag);
            }
            dd($tags);
        }

        $this->validate(request(), [
        'title' => 'required',
        'body' => 'required',
        // 'tag' => 'nullable|string'
        ]);

        $post = Post::create([
            'title' => request('title'),
            'body' => request('body'),
            'user_id' => auth()->id()
        ]);


        session()->flash('message', 'Your post has been published!');

        return redirect('/');
    }

I'm trying to figure out how to attach the array of tags to the created post.

Any help is very appreciated. Thanks :-)

0 likes
4 replies
Dry7's avatar

@joefly

class Post extends Model
{
    protected $casts = [
        'tags' => 'array',
    ];
}

public function store()
    {
        $tags = [];
        if (!empty($_POST['tags'])) {
            foreach ($_POST['tags'] as $tag) {
                array_push($tags, $tag);
            }
            dd($tags);
        }

        $this->validate(request(), [
        'title' => 'required',
        'body' => 'required',
        //'tags' => 'nullable|array'
        ]);

        $post = Post::create([
            'title' => request('title'),
            'body' => request('body'),
            'user_id' => auth()->id(),
            'tags' => $tags
        ]);

        session()->flash('message', 'Your post has been published!');

        return redirect('/');
    }
joefly's avatar

@Dry7

Hey, thanks for the response :-)

I probably should have mentioned that I have three tables, 'posts', 'tags' and a 'post_tag' pivot table...

These are the same tables that Jefferey uses in his tutorial.

Will the above method work with these three tables?

If not, any idea how to make it work?

Thanks again :-)

Dry7's avatar

@joefly create relationship

public function tags()
    {
        return $this->belongsToMany('App\Tag');
    }

and use $post->tags()->sync([1, 2, 3]); (tag ids)

joefly's avatar

Awesome, thanks @Dry7

Finally got it to work with the following:

        $tags = [];
        if (!empty($_POST['tags'])) {
            foreach ($_POST['tags'] as  
            $tag=>$id) {
                array_push($tags, $id);
                $post->tags()->sync($tags);
            }
        }

Thank for your help :-)

Please or to participate in this conversation.