Support the ongoing development of Laravel.io →
Blade Validation
Last updated by @ajax30 1 month ago.
0

Firstly you are passing tags that are associated with the article. You also need to pass list of all tags, not just specific to this article. So you need to do something like this

public function edit($id)
{
    $article = Article::find($id);
    
    // Get tags attached to the article
    $selectedTags = $article->tags->pluck('id')->toArray();  // Get the IDs of the tags related to the article

    return view('dashboard.edit-article', [
        'categories' => $this->categories(),
        'tags' => $this->tags(),
        'article' => $article,
        'selectedTags' => $selectedTags // Pass selected tags to the view
    ]);
}

Then in you blade you should do:

<select name="tags[]" id="tags" class="form-control" multiple="multiple">
    @foreach ($tags as $tag)
        <option value="{{ $tag->id }}" 
            {{ in_array($tag->id, $selectedTags) ? 'selected' : '' }}>
            {{ $tag->name }}
        </option>
    @endforeach
</select>

Lastly, in your update method, you use the attach() method which simply adds the tags without removing the old ones. You might want to do something like this:

if ($request->has('tags')) {
        $article->tags()->sync($request->tags);  // Use sync to update tags
    } else {
        // If no tags are selected, you might want to detach all existing tags
        $article->tags()->detach();
    }

sync() updates the tags for the article: it will remove any tags that are not in the provided list and add any that are missing.

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Razvan ajax30 Joined 2 Oct 2021

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.