Laravel, get last insert id using Eloquent

匿名 (未验证) 提交于 2019-12-03 02:11:02

问题:

I'm currently using this code to insert data in a table:

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);     } }

And I want to return the last ID inserted but I don't know how to get it.

Kind regards!

回答1:

After save, $data->id should be the last id inserted.

return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);


回答2:

xdazz is right in this case, but for the benefit of future visitors who might be using DB::statement or DB::insert, there is another way:

DB::getPdo()->lastInsertId();


回答3:

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 $fillable for 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 $fillable whitelist 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 create method just wraps the save method (what @xdazz cited above), so you can still pull the last created ID...

public function store() {      $input = Request::all();     $id = Company::create($input)->id;      return redirect('company/'.$id); }


回答4:

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

    $id = DB::table('users')->insertGetId(       ['email' => 'john@example.com', 'votes' => 0]     );

Refer : https://laravel.com/docs/5.1/queries#inserts



回答5:

**** For 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

$user = new User();          $user->name = 'John';    $user->save();

// Now Getting The Last inserted id

$insertedId = $user->id;  echo $insertedId ;


回答6:

In laravel 5: you can do this:

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;     } }


回答7:

Here is how we can get last inserted id in Laravel 4

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.');     }


回答8:

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);    }


回答9:

This worked for me in laravel 4.2

$data = array('username'=>Input::get('username'),               'password'=>Hash::make('password'),               'active'=>0);     $id = User::insertGetId($data);


回答10:

Use insertGetId to insert and get inserted id at the same time

From doc

If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:

By Model

$id = Model::insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);

By DB

$id = DB::table('users')->insertGetId(["name"=>"Niklesh","email"=>"myemail@gmail.com"]);

For more details : https://laravel.com/docs/5.5/queries#inserts



回答11:

after saving model, the initialized instance has the id

$report = new Report();     $report->user_id = $request->user_id;     $report->patient_id = $request->patient_id;     $report->diseases_id = $request->modality;     $isReportCreated = $report->save();     return $report->id;  // this will return the saved report id


回答12:

After saving a record in database, you can access id by $data->id

return Response::json(['success' => true, 'last_insert_id' => $data->id], 200)


回答13:

In Laravel 5.2 i would make it as clean as possible:

public function saveContact(Request $request, Contact $contact) {    $create = $contact->create($request->all());    return response()->json($create->id,  201); }


回答14:

For Laravel, If you insert a new record and call $data->save() this function executes an INSERT query and returns the primary key value (i.e. id by default).

You can use following code:

if($data->save()) {     return Response::json(array('status' => 1, 'primary_id'=>$data->id), 200); }


回答15:

After

$data->save()

$data->id will give you the inserted id,

Note: If your autoincrement column name is sno then you should use $data->sno and not $data->id



回答16:

public function store( UserStoreRequest $request ) {     $input = $request->all();     $user = User::create($input);     $userId=$user->id  }


回答17:

Using Eloquent Model

$user = new Report();         $user->email= 'johndoe@example.com';   $user->save(); $lastId = $user->id;

Using Query Builder

$lastId = DB::table('reports')->insertGetId(['email' => 'johndoe@example.com']);


回答18:

For get last inserted id in database You can use

$data = new YourModelName; $data->name = 'Some Value'; $data->email = 'abc@mail.com'; $data->save(); $lastInsertedId = $data->id;

here $lastInsertedId will gives you last inserted auto increment id.



回答19:

After Saving $data->save(). all data is pushed inside $data. As this is an object and the current row is just saved recently inside $data. so last insertId will be found inside $data->id.So the Resospnse code will be...

return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);


回答20:

You can do this:

$result=app('db')->insert("INSERT INTO table...");  $lastInsertId=app('db')->getPdo()->lastInsertId();


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!