douxiong2738 2018-08-26 21:43
浏览 91
已采纳

使用Multiselect进行Laravel数组搜索

Hello Stackoverflow Community,

I am wondering if you could help with a nagging problem that I've had for the last few days that myself and a friend cannot seem to solve.

I currently have two Models - Newsletters and Tags. Newsletters contains various information, one column in particular is called tags which implodes the values when storing and exploding the selected values on the front end.

The particular section I am working on is the edit functionality.

Currently my edit function shows as follows

 public function edit($id, Tag $tag)
{

    $tags = Tag::all();
    $newsletter = Newsletter::find($id);
    $tagged = $newsletter->tags; 
    $selected = explode(",", $tagged);

    // dd($selected);
    return view('newsletter.edit', compact('newsletter', 'tags', 'selected'));
}

My front end edit blade file is as follows:

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

However - it is only passing through one value, and although selected passes the array of values, it does not seem to check against all of them to make all the options selected.

Therefore only one of the 3 options is selected.

I know that I may not be doing it the way most people would with pivot tables, I've been trying to understand some basics and played around in the way I knew how to work it before I got stuck here.

  • 写回答

1条回答 默认 最新

  • doulangpeng3933 2018-08-27 00:05
    关注

    I use @if @endif instead of ? : statements.

    Try to change your code like this

    <select name="tags[]" class="form-control" multiple="multiple" id="tags">         
        @foreach ($tags as $tag)
           <option value="{{ $tag->name}}" @if(in_array($tag->name, $selected, true)) selected @endif }}> {{$tag->name}}</option> 
        @endforeach
    </select>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化