php 使用 Laravel Eloquent 获取最后插入的 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21084833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the Last Inserted Id Using Laravel Eloquent
提问by SoldierCorp
I'm currently using the below code to insert data in a table:
我目前正在使用以下代码在表中插入数据:
<?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);
}
}
I want to return the last ID inserted but I don't know how to get it.
我想返回最后插入的 ID,但我不知道如何获取。
Kind regards!
亲切的问候!
回答by xdazz
After save, $data->idshould be the last id inserted.
save之后,$data->id应该是最后插入的 id。
$data->save();
$data->id;
Can be used like this.
可以这样使用。
return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
For updated laravel version try this
对于更新的 Laravel 版本试试这个
return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);
回答by Benubird
回答by dave
For anyone who also likes how Jeffrey Way uses Model::create()in his Laracasts 5 tutorials, where he just sends the Request straight into the database without explicitly setting each field in the controller, and using the model's $fillablefor mass assignment (very important, for anyone new and using this way): I read a lot of people using insertGetId()but unfortunately this does not respect the $fillablewhitelist so you'll get errors with it trying to insert _token and anything that isn't a field in the database, end up setting things you want to filter, etc. That bummed me out, because I want to use mass assignment and overall write less code when possible. Fortunately Eloquent's createmethodjust wraps the save method (what @xdazz cited above), so you can still pull the last created ID...
对于那些也喜欢 Jeffrey WayModel::create()在他的 Laracasts 5 教程中使用方式的人,他只是将请求直接发送到数据库中,而没有明确设置控制器中的每个字段,并使用模型$fillable进行批量分配(非常重要,对于任何新手和使用这种方式):我读了很多人使用insertGetId()但不幸的是这不尊重$fillable白名单所以你会在尝试插入 _token 和任何不是数据库字段的东西时出错,最终设置你想要的东西过滤器等。这让我很沮丧,因为我想使用批量分配并在可能的情况下整体编写更少的代码。幸运的是,Eloquent 的create方法只是封装了 save 方法(上面引用的@xdazz),所以你仍然可以拉取最后创建的 ID...
public function store() {
$input = Request::all();
$id = Company::create($input)->id;
return redirect('company/'.$id);
}
回答by Aamir
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
如果表有自动递增的 id,则使用 insertGetId 方法插入一条记录,然后检索该 ID:
$id = DB::table('users')->insertGetId([
'email' => '[email protected]',
'votes' => 0
]);
回答by Majbah Habib
**** For Laravel ****
**** 对于 Laravel ****
Firstly create an object, Then set attributes value for that object, Then save the object record, and then get the last inserted id. such as
首先创建一个对象,然后为该对象设置属性值,然后保存对象记录,然后获取最后插入的id。如
$user = new User();
$user->name = 'John';
$user->save();
// Now Getting The Last inserted id
// 现在获取最后插入的 id
$insertedId = $user->id;
echo $insertedId ;
回答by Mujibur
In laravel 5: you can do this:
在laravel 5:你可以这样做:
use App\Http\Requests\UserStoreRequest;
class UserController extends Controller {
private $user;
public function __construct( User $user )
{
$this->user = $user;
}
public function store( UserStoreRequest $request )
{
$user= $this->user->create([
'name' => $request['name'],
'email' => $request['email'],
'password' => Hash::make($request['password'])
]);
$lastInsertedId= $user->id;
}
}
回答by user28864
This worked for me in laravel 4.2
这在 Laravel 4.2 中对我有用
$id = User::insertGetId([
'username' => Input::get('username'),
'password' => Hash::make('password'),
'active' => 0
]);
回答by ngakak
Here's an example:
下面是一个例子:
public static function saveTutorial(){
$data = Input::all();
$Tut = new Tutorial;
$Tut->title = $data['title'];
$Tut->tutorial = $data['tutorial'];
$Tut->save();
$LastInsertId = $Tut->id;
return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);
}
回答by Qamar Uzman
Here is how we can get last inserted id in Laravel 4
这是我们如何在 Laravel 4 中获取最后插入的 id
public function store()
{
$input = Input::all();
$validation = Validator::make($input, user::$rules);
if ($validation->passes())
{
$user= $this->user->create(array(
'name' => Input::get('name'),
'email' => Input::get('email'),
'password' => Hash::make(Input::get('password')),
));
$lastInsertedId= $user->id; //get last inserted record's user id value
$userId= array('user_id'=>$lastInsertedId); //put this value equal to datatable column name where it will be saved
$user->update($userId); //update newly created record by storing the value of last inserted id
return Redirect::route('users.index');
}
return Redirect::route('users.create')->withInput()->withErrors($validation)->with('message', 'There were validation errors.');
}
回答by Niklesh Raut
Use insertGetIdto insert and get inserted idat the same time
使用insertGetId插入和获得插入id在同一时间
From doc
来自文档
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
如果表有自动递增的 id,则使用 insertGetId 方法插入一条记录,然后检索该 ID:
By Model
经过 Model
$id = Model::insertGetId(["name"=>"Niklesh","email"=>"[email protected]"]);
By DB
经过 DB
$id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"[email protected]"]);
For more details : https://laravel.com/docs/5.5/queries#inserts

