Chad Priddle
Chad Priddle

Reputation: 672

Laravel form model binding with dropdown thats populated form table

I have a form in Laravel 5.1 that uses a dropdown menu that is populated form a db table. When the form is in edit mode I want the dropdown menu item to be selected that matches the id that is already in the table in addition to the other results from the db table.

Company table

array([ 'id' => 1, 'name' => 'ABC Company', 'lead' => 2]);

Lead table

array([ 
    array(['id' => 1, 'lead_name' => 'Yellow Pages']),
    array(['id' => 2, 'lead_name' => 'Internet']),
    array(['id' => 3, 'lead_name' => 'Other'])
]);

CompanyController.php

public function edit($id)
{
    $data = Company::where('id', $id)->first();
    $leads = Lead::lists('lead_name', 'id');
    return view('company.edit', compact('data', 'leads'));
}

company/edit.blade.php

{!! Form::model($data, ['method' => 'PATCH', 'action' => ['CompanyController@update', $data->id], 'class' => 'form-horizontal']) !!}
{!! Form::select('leads', $leads, null, ['class' => 'selectpicker']) !!}

What I'm trying to accomplish is when I edit id '1' I want the dropdown menu to show id '2' selected with he value of 'Internet' and then obviously the user can select the other 2 options and then update the table like normal.

Is it possible to use model binding in addition to a dropdown menu? Currently the menu populates but does not have id 2 selected.

Upvotes: 0

Views: 1188

Answers (1)

djt
djt

Reputation: 7535

1) Did you close the form properly with Form::close ?

2) It seems your $leads array may be backward. Should it not be?:

$leads = Lead::lists('id', 'lead_name');

Upvotes: 1

Related Questions