douquanzhan0315
2016-06-22 13:20
浏览 333
已采纳

如何在Laravel中获取最后插入的ID?

Here is my code

 $users = DB::table('users')->insert(array(
            'email_id' => $email_id,
            'name' => $name,
        ));

         $lastInsertedID = $users->lastInsertId();

         return $lastInsertedID;

I want to get last inserted id for particular record. I have tried using Eloquent ORM. but it didn't work.

Any help would be grateful.

Thank You.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongmou9260 2016-06-22 13:23
    已采纳

    Use insertGetId()

    $id = DB::table('users')-> insertGetId(array(
            'email_id' => $email_id,
            'name' => $name,
    ));
    
    点赞 评论
  • dongyong9224 2016-07-25 06:36

    Follow the code to get last inserted id by using ->insert()

    $lastInsertedID = DB::table('users')
                         ->insert( array(
                                       'email_id' => $email_id,
                                       'name' => $name
                                   )
                         )
                        ->lastInsertId();
    
    点赞 评论
  • duandu9260 2017-06-24 05:04

    Do you mean you inserted record id? You can get the following way:

    //UserController.php

    $user  = new User;
    $user->name = $request->name;
    $user->email = $request->email;
    if($user->save()){
        echo "User's record id is ".$user->id; *//$user->id is your lastest record id*
    }
    
    点赞 评论

相关推荐 更多相似问题