我有2个表单blade.php来获取数据并保存到数据库中。但我正在做一对多的关系,那里有一只熊和许多鱼
但我不知道如何正确地做到这一点,以前我用过这个:
$bear = Bear::create(['Name' => $request->input('name_of_bear')]);
$bear->fishes()->create(['type_of_fish' => $fishType);
但它仅适用于1页,但如果我有2页,我该怎么办?我是否使用关联,闪存,会话或其他内容将数据保存到数据库中? 如果可能的话,我也可以举一些例子供参考。谢谢
page1.blade.php:
{!! Form::open(['url' => 'page1/submit']) !!}
<div class="form-group">
{{Form::label('Name', 'Name of Bear ')}}
{{Form::text('Name', '', ['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::label('bear_type', 'Type of Bear ')}}
{{Form::text('bear_type', '', ['class' => 'form-control'])}}
</div>
<div class="form-group">
{{Form::submit('Next', ['class' => 'btn btn-primary'])}}
</div>
{!! Form::close() !!}
第1页的控制器:
public function submit(Request $request)
{
$data = array();
$data['Name'] = $request->Name;
$data['bear_type'] = $request->bear_type;
$BearDetails = bear::create($data);
return redirect('http://test.dev/page2');
}
page2.blade.php
{!! Form::open(['url' => 'page2/submit']) !!}
<div class="form-group">
{{ Form::label('type_of_fish','Type of fish bear eat')}}
<input type="checkbox" id="inlineCheckbox1" name="type_of_fish[]" value="Salmon"> Salmon
<input type="checkbox" id="inlineCheckbox2" name="type_of_fish[]" value="Sardine"> Sardine
</div>
{{ Form::label('fish_location','Where is the fish located near at?')}}
<input type="checkbox" id="inlineCheckbox1" name="fish_location[]" value="Canyon"> Canyon
<input type="checkbox" id="inlineCheckbox2" name="fish_location[]" value="Rainforest"> Rainforest
</div>
{!! Form::close() !!}
</div>
<div class="form-group">
{{Form::submit('Submit', ['class' => 'btn btn-primary'])}}
</div>
第2页的控制器:
$test = array();
$test['fish_location'] = $request->fish_location;
$test['type_of_fish'] = $request->type_of_fish;
$bear = bear::create($data);
$fish = fish::create($test);
$fish->user_particular()->associate($bear);
$fish->save();
return ('thank you');
}
熊模型:
class bear extends Eloquent
{
protected $primaryKey = 'id';
public function fishs() {
return $this->hasMany('App\fish,'bear_id');
}
}
鱼模型:
class fish extends Eloquent
{
protected $fillable = array('name', 'bear_id');
// DEFINE RELATIONSHIPS
public function bears() {
return $this->belongsTo('App\bear);
}
}