407

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.

Kind regards!

Blaze
  • 16,736
  • 2
  • 25
  • 44
SoldierCorp
  • 7,610
  • 16
  • 60
  • 100
  • $id = DB::table('users')->insertGetId( array('email' => 'john@example.com', 'votes' => 0) ); – Nahid Aug 29 '21 at 09:07

32 Answers32

557

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

$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

return response()->json(array('success' => true, 'last_insert_id' => $data->id), 200);
vimuth
  • 5,064
  • 33
  • 79
  • 116
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • 2
    An object always returns an object, ofc. This is the only way to go. – Cas Bloem Nov 26 '14 at 14:11
  • 55
    Beware that if the id is NOT autoincrement, this will always return `0`. In my case the id was a string (UUID) and for this to work I had to add `public $incrementing = false;` in my model. – Luís Cruz Apr 20 '15 at 17:18
  • 3
    @milz I have MySQL trigger that generate the uuid for a custom field named `aid` and I have set `$incrementing = false;` but It does not returned too! – SaidbakR Apr 08 '17 at 13:29
  • @SaidbakR while true, please can you indicate the section of the Laravel doc where you got this very important information? – Damilola Olowookere May 13 '19 at 22:51
  • @DamilolaOlowookere This is what I had found in my application which uses Laravel 5.4. – SaidbakR May 14 '19 at 22:44
  • By using `$user->getKey()` you make sure, the primary key can be something else than `id`. – shaedrich Mar 30 '23 at 07:12
178

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();
Community
  • 1
  • 1
Benubird
  • 18,551
  • 27
  • 90
  • 141
81

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

Barry
  • 3,303
  • 7
  • 23
  • 42
Aamir
  • 2,173
  • 1
  • 29
  • 58
  • What you described looks like capturing last insert using Fluent. Question was about Eloquent. It would look more like: $id = Model::create('votes' => 0])->id; As described in this answer above: https://stackoverflow.com/a/21084888/436443 – Jeffz Jul 10 '18 at 22:02
  • And of course, as mentioned in other comments, don't forget that using `insert` will ignore events and `$fillable`, so take that into consideration! – Charles Wood Oct 16 '20 at 19:04
73

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);
}
dave
  • 2,288
  • 4
  • 23
  • 20
  • 2
    This example didn't work for me in 5.1, but this did: `$new = Company::create($input);` `return redirect('company/'.$new->id);` – timgavin Sep 19 '15 at 18:15
  • 2
    This assumes that the request fields name are the same as their respective database columns. Which is not always the case ( legacy codes for example).. – mosid Nov 30 '17 at 04:47
  • By using `$user->getKey()` you make sure, the primary key can be something else than `id`. – shaedrich Mar 30 '23 at 07:11
55

**** 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 ;
Majbah Habib
  • 8,058
  • 3
  • 36
  • 38
29

There are several ways to get the last inserted id. All are based on what method do you used when inserting. In your case you can get last Id like the following:

$data->save();
$data->id;

For others who need to know how can they get last inserted id if they use other insert methods here is how:

  • Using create() method

    $book = Book::create(['name'=>'Laravel Warrior']);

    $lastId = $book->id;

  • Using insertGetId()

    $id = DB::table('books')->insertGetId( ['name' => 'Laravel warrior'] ); $lastId = $id;

  • Using lastInsertId() method

    $lastId = DB::getPdo()->lastInsertId();

Reference https://easycodesolution.com/2020/08/22/last-inserted-id-in-laravel/

Abdulhakim Zeinu
  • 3,333
  • 1
  • 30
  • 37
20

This worked for me in laravel 4.2

$id = User::insertGetId([
    'username' => Input::get('username'),
    'password' => Hash::make('password'),
    'active'   => 0
]);
Barry
  • 3,303
  • 7
  • 23
  • 42
user28864
  • 3,375
  • 1
  • 25
  • 19
19

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;
    }
}
Mujibur
  • 937
  • 7
  • 12
17

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);
}
Barry
  • 3,303
  • 7
  • 23
  • 42
jsdev
  • 672
  • 6
  • 14
15

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

Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109
14

Although this question is a bit dated. My quick and dirty solution would look like this:

$last_entry = Model::latest()->first();

But I guess it's vulnerable to race conditions on highly frequented databases.

dustypaws
  • 191
  • 1
  • 8
  • 1
    Thanks! This I could use in my pipeline. So no worries about race conditions and beautiful code. – Daantje Mar 01 '20 at 19:00
13

For insert()

Example:

$data1 = array(
         'company_id'    => $company_id,
         'branch_id'        => $branch_id
     );

$insert_id = CreditVoucher::insert($data1);
$id = DB::getPdo()->lastInsertId();
dd($id);
JON
  • 965
  • 2
  • 10
  • 28
Faridul Khan
  • 1,741
  • 1
  • 16
  • 27
12

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.');
    }
Qamar Uzman
  • 1,012
  • 9
  • 4
8

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
Barry
  • 3,303
  • 7
  • 23
  • 42
Amir
  • 8,821
  • 7
  • 44
  • 48
7

You can easily fetch last inserted record Id

$user = User::create($userData);
$lastId = $user->value('id');

It's an awesome trick to fetch Id from the last inserted record in the DB.

Priyanka Patel
  • 323
  • 4
  • 15
  • two concurrent users adding the to the company model at the same time. this isn't reliable as the 1st post might get the id of the 2nd if the timing is right. the accepted answer is reliable. – Alex May 05 '20 at 17:18
  • @Alex kindly check, this is working and the best solution to get last inserted id from records. – Priyanka Patel May 08 '20 at 04:48
  • the updated solution is fine, however it requires more code than the accepted answer. Simply doing `$user->id` is enough after creating to get the inserted id. – Alex May 08 '20 at 19:10
  • 2
    This is exactly the answer I wanted on Eloquent – Eben Watts Aug 15 '22 at 10:18
  • By using `$user->getKey()` you make sure, the primary key can be something else than `id`. – shaedrich Mar 30 '23 at 07:10
4

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

Abhishek Goel
  • 18,785
  • 11
  • 87
  • 65
4

You can do this:

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

$lastInsertId=app('db')->getPdo()->lastInsertId();
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167
3

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

return Response::json(['success' => true, 'last_insert_id' => $data->id], 200)
Tayyab Hussain
  • 1,658
  • 1
  • 18
  • 21
3

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);
}
bobbybackblech
  • 1,868
  • 5
  • 20
  • 22
3

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);
}
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
HItesh Tank
  • 636
  • 1
  • 6
  • 13
2
$objPost = new Post;
$objPost->title = 'Title';
$objPost->description = 'Description';   
$objPost->save();
$recId = $objPost->id; // If Id in table column name if other then id then user the other column name

return Response::json(['success' => true,'id' => $recId], 200);
Barry
  • 3,303
  • 7
  • 23
  • 42
1

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.

PPL
  • 6,357
  • 1
  • 11
  • 30
1

The shortest way is probably a call of the refresh() on the model:

public function create(array $data): MyModel
{
    $myModel = new MyModel($dataArray);
    $myModel->saveOrFail();
    return $myModel->refresh();
}
automatix
  • 14,018
  • 26
  • 105
  • 230
1

You can also try like this:

public function storeAndLastInrestedId() {
    $data = new ModelName();
    $data->title = $request->title;
    $data->save();

    $last_insert_id = $data->id;
    return $last_insert_id;
}
ventaquil
  • 2,780
  • 3
  • 23
  • 48
1

Here it is how it worked for me, family_id is the primary key with auto increment I am using 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);
    }

Also in the Model Family file which extends Model, should have the increment set to true otherwise the above $family-->family_id will return empty

    public $incrementing = true;
  
surajav
  • 11
  • 1
  • 3
0

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.

Response code will be:

return Response::json(array('success' => true, 'last_insert_id' => $data->id), 200);
Barry
  • 3,303
  • 7
  • 23
  • 42
sabuz
  • 829
  • 8
  • 10
0

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']);
0

You can get last inserted id with same object you call save method;

$data->save();
$inserted_id = $data->id;

So you can simply write:

if ($data->save()) {
    return Response::json(array('success' => true,'inserted_id'=>$data->id), 200);
}
infomasud
  • 2,263
  • 1
  • 18
  • 12
-1
public function store( UserStoreRequest $request ) {
    $input = $request->all();
    $user = User::create($input);
    $userId=$user->id 
}
Shadow
  • 33,525
  • 10
  • 51
  • 64
  • 2
    This post was answered 3 years ago. Please edit your answer to add more explanation as to why it might help the user or how its helps solves the OP's question in a better way. – Syfer Sep 08 '17 at 11:42
  • 1
    Thank you for this code snippet, which may provide some immediate help. A proper explanation [would greatly improve](https://meta.stackexchange.com/q/114762) its educational value by showing why this is a good solution to the problem, and would make it more useful to future readers with similar, but not identical, questions. Please edit your answer to add explanation, and give an indication of what limitations and assumptions apply. Not to mention the age of the question and the low quality of your answer. – GrumpyCrouton Sep 08 '17 at 15:53
  • Beware of using this code as there is no validation here. You should not store any information without validation. – Khalilullah Nov 19 '20 at 12:00
-1

Using Eloquent Model

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;

}

Using Query Builder

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

For more methods to get Last Inserted Row id in Laravel : http://phpnotebook.com/95-laravel/127-3-methods-to-get-last-inserted-row-id-in-laravel

Karthik
  • 5,589
  • 18
  • 46
  • 78
-1

You can use $this constructor variable to achieve "Last Inserted Id Using Laravel Eloquent" (without adding any extra column) in current function or controller.

public function store(Request $request){
    $request->validate([
        'title' => 'required|max:255',
        'desc' => 'required|max:5000'
    ]);

    $this->project = Project::create([
        'name' => $request->title,
        'description' => $request->desc,
    ]);

    dd($this->project->id);  //This is your current/latest project id
    $request->session()->flash('project_added','Project added successfully.');
    return redirect()->back();

}
-2

Optional method will be:

$lastID = DB::table('EXAMPLE-TABLE')
                ->orderBy('id', 'desc')
                ->first();

$lastId = $lastProduct->id;

Source from Laravel 5.8 version