Laravel 5.1:更新文章时显示所有选定的标签

时间:2015-11-27 15:22:20

标签: php laravel foreach tags laravel-5.1

当我尝试更新某篇文章时,我有一个问题是显示所有选定的标签。

我是laravel和php的新手,所以,这是我的代码:

<select name="tags[]" class="form-control" multiple="multiple">
    @foreach($tags as $key => $value)
        @foreach($news->tags as $tag)
            <option value="{{ $key }}" @if($tag->name == $value) selected @endif>{{ $value }}</option>
        @endforeach
   @endforeach
</select>

但结果并非我实际上期望:

<select name="tags[]" class="form-control" multiple="multiple">
    <option value="1" selected="">1</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="3" selected="">3</option>
</select>

必须是这样的:

<select name="tags[]" class="form-control" multiple="multiple">
    <option value="1" selected>1</option>
    <option value="2">2</option>
    <option value="3" selected>3</option>
</select>

我该怎么做? 谢谢!

2 个答案:

答案 0 :(得分:1)

只需将选定的标签传递到视图并使用contains方法

$tags = Tag::all();
$selectedTags = $article->tags;
return view('YOUR VIEW',[
            'tags' => $tags,
            'selectedTags' => $selectedTags
        ]);

视图中:

@foreach($tags as $tag)
     <option value="{{$tag->id}}" @if ($selectedTags->contains($tag->id)) selected @endif>{{$tag->name}}</option>
@endforeach

答案 1 :(得分:0)

做这样的事情。最好将代码放在控制器中的php标签内,并将变量传递给你的视图。

<?php 
$tagsObjectArray = $news->tags->toArray();
$tagsArray = array_column($tagsObjectArray, 'name');
?>
<select name="tags[]" class="form-control" multiple="multiple">
    @foreach($tags as $key => $value)
            <option value="{{ $key }}" @if(in_array($value, $tagsArray)) selected @endif>{{ $value }}</option>
   @endforeach
</select>