我目前正在使用下面的代码在一个表中插入数据:
<?php
public function saveDetailsCompany()
{
$post = Input::All();
$data = new Company;
$data->nombre = $post['name'];
$data->direccion = $post['address'];
$data->telefono = $post['phone'];
$data->email = $post['email'];
$data->giro = $post['type'];
$data->fecha_registro = date("Y-m-d H:i:s");
$data->fecha_modificacion = date("Y-m-d H:i:s");
if ($data->save()) {
return Response::json(array('success' => true), 200);
}
}
我想返回插入的最后一个ID,但我不知道如何获取它。
亲切的问候!
这就是它是如何为我工作的,family_id是自动增量的主键,我使用Laravel7
public function store(Request $request){
$family = new Family();
$family->family_name = $request->get('FamilyName');
$family->family_no = $request->get('FamilyNo');
$family->save();
//family_id is the primary key and auto increment
return redirect('/family/detail/' . $family->family_id);
}
同样在Model Family文件中,应该将增量设置为true,否则上面的$ Family——>family_id将返回空
public $incrementing = true;
使用雄辩的模型
use App\Company;
public function saveDetailsCompany(Request $request)
{
$createcompany=Company::create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);
// Last Inserted Row ID
echo $createcompany->id;
}
使用查询生成器
$createcompany=DB::table('company')->create(['nombre'=>$request->input('name'),'direccion'=>$request->input('address'),'telefono'=>$request->input('phone'),'email'=>$request->input('emaile'),'giro'=>$request->input('type')]);
echo $createcompany->id;
获取Laravel中最后插入行id的更多方法:http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel
保存后,$data->id应该是最后插入的id。
$data->save();
$data->id;
可以这样使用。
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
更新laravel版本试试这个
return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);