Get id of last inserted record in laravel

There are lots of methods available in laravel to get the id of the last inserted record. Sometimes we need to get the id of the last inserted record to do some specific task in our application. In that case this query will help you to get the last inserted record id.

Answers 4
  • Get id using insertGetId() method in laravel

    $id = DB::table('users')->insertGetId(
        [ 'name' => 'w3codegenerator.com' ]
    );
    
    dd($id);
    
    0

    The insertGetId() method inserts the record in the table and returns the id of the record.

  • Get id using lastInsertId() method in laravel

    DB::table('users')->insert([
        'name' => 'w3codegenerator.com'
    ]);
    $id = DB::getPdo()->lastInsertId();
    dd($id);
    
    0

    This method also returns the id of the last inserted record of the table using lastInsertId() method in laravel.

  • Get id of record after save method

    //Import the product model class
    $product = new Product;
    $product->name = $request->name;
    $product->save();
    dd($product->id);
    
    0

    It will display the id of the created record using save method. Basically the save method returns the created object and you can use $product->id to get the id of the created record.

  • Get id of record after create method

    //Import User Model
    $data = User::create(['name'=>'w3codegenerator.com']);
    dd($data->id);
    
    0

    You can get the id of the created record in laravel using $data->id after the create method in laravel. Create() method returns the created object after creating the record. 

  • Back to code snippet queries related laravel