Laravel 5.5 CRUD 表单的正确方法 select

Laravel 5.5 correct way for a CRUD form select

所以我有这个 CRUD,我在其中使用相同的表单来创建和编辑条目。 我需要多种形式的 selects,在创建时(该特定字段还没有数据)我的 select 来显示占位符,但是在编辑时,我的 select 来显示存储的内容在该特定 id 字段的数据库上。所以我有: 控制器:

...
 public function create()
    {
        $house = houses::pluck('name', 'id');
        //$thisclient = null;
        $clients = client::pluck('last_name', 'id');
        $reps = user::where('role_id', 5)->orderBy('first_name')->get()->pluck('full_name', 'id');

        return view('prospects.create', compact('house', 'clients', 'reps'));
    }

...

public function edit($id)
    {
        $house = houses::pluck('name', 'id');
        //$thisclient = user::whereId($id)->first();
        $clients = client::pluck('last_name', 'id');
        $reps = user::where('role_id', 5)->orderBy('first_name')->get()->pluck('full_name', 'id');

        $prospect = Prospect::findOrFail($id);

        return view('prospects.edit', compact('prospect', 'house', 'clients', 'reps'));
    }

和我的观点: 为创造工作:

{!!Form::select('client_id', $clients, null, ['class' => 'form-control', 'placeholder' => 'Please Select'] ) !!}

正在编辑:

{!! Form::select('client_id', $clients, $prospect->client_id, ['class' => 'form-control'] ) !!}

我在这里有 2 个问题,如果我有 null 作为我的 selected 字段,它不会在 edit 上带来 selected 数据,如果我有 $prospect->client_id ,它将 return 在 create 上出错,因为还没有数据。 我试图通过在控制器上创建一个变量 $thishouse 并将其传递给 return view('prospects.create', compact('house', 'thisclient','clients', 'reps')); 和视图 Form::select('client_id', $clients, $thisclient, ['class' => 'form-control'] ) !!} 上的视图来解决这个问题,但是当有多种形式 select 时看起来有点脏小...

第二个麻烦是如果我在编辑上留下占位符,它会显示占位符,而不是 $prospect->client_id 本身。

实现所有这些并使用相同的表单进行创建和编辑的最好和最简单的方法是什么? 谢谢

您可以使用 Form::open 和 Form::model 来创建和编辑。例如,您可以在视图中设置:

@if(isset($prospect))
    {!! Form::model($prospect, ['action' => ['ProspectController@update', $prospect->id], 'method' => 'patch']) !!}
@else
    {!! Form::open(array('action' => 'ProspectController@store', 'method' => 'POST')) !!}
@endif

然后您可以像这样创建 select:

{!! Form::select('client_id', $clients, old('client_id'), ['class' => 'form-control'] ) !!}

因此,当您编辑时,Laravel 将 select 来自模型函数变量的属性。

并且由于您正在使用 Laravel 5.5,您也可以使用 @isset 指令。