如果选项 id 在刀片视图的数组列表中,Laravel 将选项设置为选中

我在控制器中进行了查询并将其发送到我的刀片:


public function editContractorAssociation(DeveloperContractorAssociation $developer_contractor_association, Request $request)

    {

        $id = $request->id;

        $developer_contractor_association = DeveloperContractorAssociation::whereHas('defect_types', function ($query) use($id) {

            $query->where('developer_contractor_associations.id', $id);

        })->orwhereHas('contractor', function ($query) use($id) {

            $query->where('developer_contractor_associations.id', $id);

        })->first();

        return view('dev-admin.contractors.associations.edit', ['developer_contractor_association' => $developer_contractor_association]);

    }

当我打电话给{{ $developer_contractor_association->defect_types }}我的刀片时,我得到了这个:


[

    {

        "id":2,

        "title":"Wiring",

        "details":"Fix wiring",

        "created_by":"22",

        "created_at":"2019-09-04 11:39:48",

        "updated_at":"2019-09-04 11:39:48",

        "deleted_at":null,

        "is_custom":1,

        "developer_id":1,

        "pivot":{"dca_id":87,"defect_type_id":2}},

        {"id":3,"title":"Plumbing",

            "details": "Fix Pipe",

            "created_by":"22",

            "created_at":"2019-09-04 11:40:07",

            "updated_at":"2019-09-04 11:40:07",

            "deleted_at":null,

            "is_custom":1,

            "developer_id":1,

        "pivot":{"dca_id":87,"defect_type_id":3}

    }

]

现在我有一个选择字段,列出了所有存在的缺陷类型:


<select class="selectpicker {{ $errors->has('defect-type-id') ? 'is-invalid' : '' }}" name="defect-type-id[]" id="defect-type-id" multiple data-style="selectpicker-style" data-width="100%" title="Defect Types">

    @foreach(App\DefectType::select('id','title')->get() as $defect_type)

        <option value="{{$defect_type->id}}">{{$defect_type->title}}</option>

    @endforeach

</select>



qq_遁去的一_1
浏览 102回答 1
1回答

哈士奇WWW

假设你的defect_types关系返回一个 Laravel Collection,你可以使用几个 Collection 方法:@foreach(App\DefectType::select('id','title')->get() as $defect_type)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; <option value="{{$defect_type->id}}"&nbsp; &nbsp; &nbsp; &nbsp; @if($developer_contractor_association->defect_types->pluck('id')->contains($defect_type->id))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selected&nbsp; &nbsp; &nbsp; &nbsp; @endif&nbsp; &nbsp; >&nbsp; &nbsp; &nbsp; &nbsp; {{$defect_type->title}}&nbsp; &nbsp; </option>@endforeachpluck('id')返回一个 Collection ,defect_type id然后您可以检查 all 的当前迭代defect_type是否在该 Collection 中contains($defect_type->id)。您可以使用containsstrict()代替,contains()因为它会进行严格的比较。
打开App,查看更多内容
随时随地看视频慕课网APP