How can I display selected options of a multiple select in this Laravel 8 application?
12:30 09 Feb 2025

I am working on a blogging application in Laravel 8.

In the form I use for editing articles, I have a multiple-select element.

I want the form to show the tags that have been selected. For this purpose, I did the following in the view:



@php
  $selected = explode(",", $tags);
@endphp


In the controller, I have:

public function edit($id)
  {
    $article = Article::find($id);
    return view(
      'dashboard/edit-article',
      [
        'categories' => $this->categories(),
        'tags' => $this->tags(),
        'article' => $article
      ]
    );
  }

public function update(Request $request, $id)
{
    $validator = Validator::make($request->all(), $this->rules, $this->messages);

    if ($validator->fails()) {
      return redirect()->back()->withErrors($validator->errors())->withInput();
    }

    $fields = $validator->validated();
    $article = Article::find($id);

    // If a new image is uploaded, set it as the article image
    // Otherwise, set the old image...
    if (isset($request->image)) {
      $imageName = md5(time()) . Auth::user()->id . '.' . $request->image->extension();
      $request->image->move(public_path('images/articles'), $imageName);
    } else {
      $imageName = $article->image;
    }

    $article->title = $request->get('title');
    $article->short_description = $request->get('short_description');
    $article->category_id = $request->get('category_id');
    $article->featured = $request->has('featured');
    $article->image = $request->get('image') == 'default.jpg' ? 'default.jpg' : $imageName;
    $article->content = $request->get('content');
    // Save changes to the article
    $article->save();
    //Attach tags to article
    if ($request->has('tags')) {
      $article->tags()->attach($request->tags);
    }

    return redirect()->route('dashboard.articles')->with('success', 'The article titled "' . $article->title . '" was updated');
}

For a reason I have not been able to spot, this does not work. That means the article's tags are not selected in the