如何解决创建后如何使用Laravel在db中显示最后插入的id
患者控制器:
public function store(Request $request)
{
$input = request()->all();
Patient::create($input);
dd($input->id);
// return redirect()->route('medical.create',compact('input'));
}
这是我的medical.create视图
{!! Form::model($input,[
'method' => 'POST','action' => ['MedicalController@store',$input->id]
]) !!}
<div class="row">
<div class="col-md-4">
<div class="form-group">
{{Form::label('patient_id','Patient no:')}}
{{Form::text('patient_id',null,array('class' => 'form-control') )}}
</div>
</div>
</div>
{!! Form::close() !!}
我想在存储后获取最后插入的ID,并以下一种形式显示最后一个ID,但这是在屏幕上出现的错误:
Trying to get property 'id' of non-object
这是我的“患者”表:
解决方法
您可以通过在创建Patient
对象时将其保存在变量中来做到这一点:
public function store(Request $request)
{
$input = request()->all();
$patient = Patient::create($input); // Save it in variable
dd($patient->id); //Now you can access patient id here
// return redirect()->route('medical.create',compact('patient')); //Also you can pass it to your view
}
,
您可以使用以下代码之类的ID,并在代码中进行最少的更改
$input = request()->all();
$input = Patient::create($input);
dd($input->id);
// return redirect()->route('medical.create',compact('input'));
,
在通过批量分配保存数据后,您可以检索ID:
public function store(Request $request)
{
$input = request()->all();
$patient = new Patient($input); // fill model with mass assignments
$patient->save() // save instant
$id = $patient->id; //retrive id
}
,
重定向时不能使用压缩。试试这个:
患者控制器:
public function store(Request $request)
{
$input = request()->all();
$patient = Patient::create($input);
$patient = DB::table('patients')->get()->last();
return redirect()->route('medical.create')->with('patient_id',$patient->id);
}
这是我的medical.create视图
{!! Form::model($input,[
'method' => 'POST','action' => ['MedicalController@store',session('patient_id')]
]) !!}
<div class="row">
<div class="col-md-4">
<div class="form-group">
{{Form::label('patient_id','Patient no:')}}
{{Form::text('patient_id',null,array('class' => 'form-control') )}}
</div>
</div>
</div>
{!! Form::close() !!}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。