为什么Laravel控制器store()将空值插入数据库

时间:2019-07-08 03:58:36

标签: laravel laravel-5

我想通过控制器存储功能将数据插入到MySQL数据库表中,但是它总是插入空值。我不知道问题出在哪里。

模型

class Office extends Model
{
    protected $fillable = array('office_name_local', 'office_english_name');
}

控制器

public function store(Request $request)
{
    $validatedData = $request->validate([
        'office_name_local' => 'required', 'office__name_english' => 'required'
    ]);

    $office = Office::create($validatedData);

    return redirect('/createOffice')->with('success', 'Office is successfully saved');
}

刀片

<form method="POST" class="form-horizontal well col-xs-8 col-xs-offset-2"
      action="{{route('OfficeController.store')}}">
    <div class="form-group row">
        <div class="col-md-6">
            <label for="office_name_local"> local name</label>
            <input type="text" class="form-control" name="office_name_local" required>
        </div>
    </div>
    <div class="form-group row">
        <div class="col-md-6">
            <label for="office_name_english"> English name</label>
            <input type="text" class="form-control" name="office_name_english" required>
        </div>
    </div>
    <div class="form-group row mb-0">
        <div class="col-md-6 offset-md-4">
            <button type="submit" class="btn btn-primary">
                {{ __('add') }}
            </button>
        </div>
    </div>
</form>   

我的路线

Route::get('createOffice','OfficeController@create')->name('createOffice'); 
Route::post('createOffice','OfficeController@store')->name('OfficeController.store');   

1 个答案:

答案 0 :(得分:0)

//控制器

public function store(Request $request)
{
 if ($request->method() == 'POST') {
      $rules = array(
      'office_name_local' => 'required',
      'office__name_english' => 'required'
      );
 $validator = Validator::make($request->all(), $rules);
            if (!$validator->fails()) {
$officeObj = new Office();
    $officeId = $officeObj->create($request);

    return redirect('/createOffice')->with('success', 'Office is successfully saved');
}
}

//型号

function create($request) {
$this->office_name_local = $request->office_name_local;
$this->office__name_english = $request->office__name_english;
$this->save();
 return $this->id;
}