如何将下拉列表中的选定值传递给控制器​​然后保存

时间:2018-08-17 04:40:35

标签: php laravel laravel-5

大家好,请帮助我如何将下拉列表中的选定数据传递到控制器以进行保存。这是我正在使用的代码:
视图:

 <div class="form-group">
     {{Form::label('IncomeExpense', 'Income&Expense')}}
     {{Form::select('IncomeExpense', array( 'Expense', 'Income'),null,['class'=>'form-control'])}}
    </div>


<div class="form-group">
            {{Form::label('', 'Income')}} 
            {{Form::select('IncomeId', $incomes,null,['class'=>'form-control','id'=>'Income',  'onChange'=>'validate()'])}}
           </div>

控制器:

 $incexp= new IncomeExpenses();
 $incexp->IncomeExpense=$request->input('IncomeExpense');
 $incexp->save();

模型类

class IncomeExpenses extends Model
{
    public function income(){
        return $this->hasOne(Income::class);
    }
    public function expense(){
        return $this->hasOne(Expenses::class);
    }
}

1 个答案:

答案 0 :(得分:1)

编辑

尝试使用$incexp->IncomeExpense=$request->IncomeExpense;代替$request->input('IncomeExpense');


这就像发送其他任何表格一样,您是否仅在下拉菜单时遇到麻烦?

您的表单打开呼叫应如下所示:

{!! Form::open(['method' => 'POST',  'url' => url('yourURL')] ) !!}

取决于Laravel 5的版本...您将不得不在route.php或web.php文件中设置路由

Route::post('yourURL', 'YourController@store');

您的存储方法应类似于

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request)
{
    $validator = Validator::make($request->all(), [
        'yourInput'                 => 'required',
    ]);

    if ($validator->fails()) {
        return redirect()->intended('yourURL')->withErrors($validator)->withInput();
    }

    DB::beginTransaction();
    $incexp= new IncomeExpenses();
    $incexp->IncomeExpense=$request->IncomeExpense;
    $incexp->save();

    DB::commit();

    return redirect()->intended('yourURL/' . $incexp->id );
}