Laravel Foreign Keys Drop-down List

南楼画角 提交于 2019-12-21 20:15:50

问题


I have 2 tables:

  • CUSTOMERS(id, full_name, company_id)
  • COMPANIES(id, company_name)

I already created the relation between the two tables, and it's working fine because I can display company name in the customers view like this: $customer->company->company_name

I'm now having issues with the customer create and edit views. I'd like to have the company_name as a drop-down (Form Select) in create and edit views. Then insert the company id to the CUSTOMERS table.


回答1:


You need to supply Form::select with companies as an array('id'=>'name'):

// Controller, repo or wherever you want it:
$companies = Company::lists('company_name','id');

// $companies passed to the view, then in the create view:
{{ Form::select('company_id', $companies, null, $options) }}

// edit view:
{{ Form::model($customer, array('route' => array('YourCustomerUpdateRoute', $customer->id))) }}
...
{{ Form::select('company_id', $companies, null, $options) }} 
// form model binding autopopulates the form, so correct option will be selected

After submitting the form validate the input, check if provided company_id exists on the companies table and save the customer, that's all.




回答2:


The Jarek Tkaczyk answer is excellent. However if you want make a default value for create form and avoid pre-select the first element in the $companies array, you can do something like this in your controller:

$companies = Company::lists('company_name','id');
$companies = array('0' => 'Select Company') + $companies;

Then pass $companies array to the view as Jarek Tkaczyk said.

Note:

I did

$companies = array('0' => 'Select Company') + $companies;

in order to preserve the array keys.



来源:https://stackoverflow.com/questions/23283522/laravel-foreign-keys-drop-down-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!