我已经有一段时间了,我想做的是从选择框中获取所选值的 id。使用这个片段,它没有得到 id,我想知道为什么。我很困惑什么可能是错的
此代码用于获取所选值的 id:
private static function compareCompany(ProductRequest $productRequest){
$companyPicked = $productRequest->companyname;
$listedCompanies = Company::where('user_id', '=', Auth::user()->id);
$companies = new Company;
if($companies->user_id === Auth::user()->id)
{
foreach($listedCompanies as $company) {
if($company->companyname === $companyPicked)
{
return $company->id;
}
}
}
}
这是使用为公司返回的 id 创建新产品
public function store(ProductRequest $productRequest)
{
$product = new Product;
$company = new Company;
if($productRequest->isMethod('post')){
$product->user_id = Auth::user()->id;
$product->company_id = $this->compareCompany($productRequest);
$product->companyname = $productRequest->companyname;
$product->productname = $productRequest->productname;
$product->save();
return redirect()->route('companyindex')->with('message', 'Your question has been posted.');
}else{
return redirect('company-create')->withErrors($productRequest)->withInput();
}
}
这是视图:
<p>{!! Form::select('companyname', array('' => 'Select a Company') + $listCompanies) !!} </p>
这是用于将返回值绑定到视图的代码:
public function create()
{
$listCompanies = Company::where('user_id', '=', Auth::user()->id)->orderBy('companyname', 'desc')->lists('companyname', 'companyname')->toArray();
return view('product.create')
->with('listCompanies', $listCompanies);
}