Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Foreign Keys Drop-down List

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.

enter

like image 639
kenold Avatar asked Jun 05 '26 16:06

kenold


1 Answers

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.

like image 139
Jarek Tkaczyk Avatar answered Jun 08 '26 15:06

Jarek Tkaczyk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!