te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>php - In Laravel, how can I keep the selected options of a multiselect on an invalid form? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - In Laravel, how can I keep the selected options of a multiselect on an invalid form? - Stack Overflow

programmeradmin3浏览0评论

I am working on a blogging application in Laravel 8.

There is the option to add tags to articles. There is a many-to-many relationship between articles and tags. I have an article_tag pivot table.

In the Tag model I have:

class Tag extends Model
{
   use HasFactory;

   protected $fillable = ['name'];

   public function articles()
   {
       return $this->belongsToMany(Article::class);
   } 
}

To the Article model I have added the tags() method

public function tags()
{
    return $this->belongsToMany(Tag::class)->as('tags');
}

I the ArticleController controller, I have two methods for editing and updating an article:

public function edit($id)
  {
    $article = Article::find($id);
    $attached_tags = $article->tags()->get()->pluck('id')->toArray();
    
    return view(
      'dashboard/edit-article',
      [
        'categories' => $this->categories(),
        'tags' => $this->tags(),
        'attached_tags' => $attached_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->tags[] = $request->get('tags[]');
    $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 (isset($request->tags)) {
      $article->tags()->sync($request->tags);
    } else {
      $article->tags()->sync([]);
    }

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

In edit-article.blade.php, I use a multiselect element to assign tags to articles:

<div class="row mb-2">
    <label for="tags" class="col-md-12">{{ __('Tags') }}</label>

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

The problem I am faced with is that when I edit the tags list, the <select> element above does not keep the selected tags if the form is invalid because of validation errors on other form fields.

Where is my mistake?

I am working on a blogging application in Laravel 8.

There is the option to add tags to articles. There is a many-to-many relationship between articles and tags. I have an article_tag pivot table.

In the Tag model I have:

class Tag extends Model
{
   use HasFactory;

   protected $fillable = ['name'];

   public function articles()
   {
       return $this->belongsToMany(Article::class);
   } 
}

To the Article model I have added the tags() method

public function tags()
{
    return $this->belongsToMany(Tag::class)->as('tags');
}

I the ArticleController controller, I have two methods for editing and updating an article:

public function edit($id)
  {
    $article = Article::find($id);
    $attached_tags = $article->tags()->get()->pluck('id')->toArray();
    
    return view(
      'dashboard/edit-article',
      [
        'categories' => $this->categories(),
        'tags' => $this->tags(),
        'attached_tags' => $attached_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->tags[] = $request->get('tags[]');
    $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 (isset($request->tags)) {
      $article->tags()->sync($request->tags);
    } else {
      $article->tags()->sync([]);
    }

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

In edit-article.blade.php, I use a multiselect element to assign tags to articles:

<div class="row mb-2">
    <label for="tags" class="col-md-12">{{ __('Tags') }}</label>

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

The problem I am faced with is that when I edit the tags list, the <select> element above does not keep the selected tags if the form is invalid because of validation errors on other form fields.

Where is my mistake?

Share Improve this question edited Feb 18 at 6:22 Abdulla Nilam 38.6k18 gold badges68 silver badges95 bronze badges Recognized by PHP Collective asked Feb 17 at 22:19 Razvan ZamfirRazvan Zamfir 4,6667 gold badges47 silver badges282 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

There are few errors in this (optimizations too)

  1. Remove this line

    $article->tags[] = $request->get('tags[]'); // $article->tags()->sync will do the job
    
  2. Change this

     if ($request->has('tags')) { # changed
         $article->tags()->sync($request->tags);
     } else {
         $article->tags()->sync([]);
     }
    
  3. In view

    @php
        // Use old input if present, otherwise use the attached tags from the article.
        $selectedTags = old('tags', $attached_tags);
    @endphp
    
    <div class="row mb-2">
        <label for="tags" class="col-md-12">{{ __('Tags') }}</label>
        <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>
    </div>
    

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论