如何在 select 选项 (parent_id) 中显示默认值?

How to show default value in select option (parent_id)?

我试图在 Laravel 5.8 中成功保存 Categoryparent_id,但我现在想编辑类别。

CategoryController.php

public function edit(Category $category)
{
    return view('Admin.categories.edit', compact('category'));
}

public function update(CategoryRequest $request, Category $category)
{
    $category->update($request->all());

    return redirect(route('categories.index'));
}

edit.blade.php

<form action="{{ route('categories.update', $category->id) }}" method="post">
    {{ method_field('PATCH') }}
    {{ csrf_field() }}
    @include('Admin.layouts.errors')
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" class="form-control" value="{{ old('name') ? : $category->name  }}" id="name" name="name">
    </div>
    <div class="form-group">
        <label for="parent_id">Sub Category</label>
        <select class="form-control" id="parent_id" name="parent_id" data-live-search="true">
            @foreach(\App\Category::all() as $category)
                <option value="{{ $category->id }}" {{ trim($category->id) , $category->pluck('id')->toArray() ? 'selected' : ''  }}>{{ $category->name }}</option>
            @endforeach
        </select>
    </div>
    <button type="submit" class="btn btn-primary">Save</button>
</form>

比如我在数据库中有以下分类

id          name            parent_id

1       Software        0
2       Hardware        0
3       Photoshop       1
4       CoredDraw       1

如果用户,例如selects CorelDraw for edit,打开edit for it。 Select name 输入标签,写CorelDraw。 Select parent_id 选项标签 select 软件。因为这是 parent_id is = 0.

You need to do some basic improvement in your code, Make a practice of fire query in the model or in the controller

Blade 文件不用于从数据库加载数据

控制器

public function edit(Category $category)
{
    $allCategory = \App\Category::all();
    return view('Admin.categories.edit', compact('category','allCategory'));
}

Blade

<select class="form-control" id="parent_id" name="parent_id" data-live-search="true">
    <option value="">Select Parent</option> 
    @foreach($allCategory as $cate)
        <option value="{{ $cate->id }}" {{ $category->id == $cate->id ? 'selected' : ''  }}>{{ $cate->name }}</option>
    @endforeach
</select>

Once the user starts typing different category name you need to reset the select box using any client side script