Libin Joseph
Libin Joseph

Reputation: 29

How to return last added id in Laravel

My controller code for adding data using laravel is given below. $request is globally declared

public function createEnquiry(Request $request){
    //my table is enquirydetails
    DB::table('enquirydetails')->insert(
        ['name' =>$request->input('name'),
        'address' =>$request->input('address') ,
        'phone' =>$request->input('phone') ,
        'created_at' => date("Y-m-d H:i:s") ,
        'updated_at' => date("Y-m-d H:i:s"),
        ]); 
}

I need to return the id after it added to db. This code is a Lumen api db insertion code. Web path is

$router->group(['prefix' => 'Enquiry','namespace' => 'Enquiry'], 
function($router){
    $router->post('new','EnquiryController@createEnquiry');
});

Upvotes: 0

Views: 122

Answers (3)

JIJOMON K.A
JIJOMON K.A

Reputation: 1280

please assign Db:: to a variable example $result, then print it

print_r($result);

Upvotes: 0

Bilal Ahmed
Bilal Ahmed

Reputation: 4066

Use insertGetId method to insert a record and then retrieve the ID:

$id = DB::table('tableName')->insertGetId(
          ['name' => $request->input('name'),
           'address'=> $request->input('address')]
);
print_r($id);

for more details read Manual

Upvotes: 6

Dexter Bengil
Dexter Bengil

Reputation: 6625

First you should create a Model for your enquirydetails table. It could be like this:

EnquiryDetail.php - Model

And when doing the insertion, you can just easily do this

$detail = EnquiryDetail::create([
    'name' =>$request->input('name'),
    'address' =>$request->input('address') ,
    'phone' =>$request->input('phone') ,
    'created_at' => date("Y-m-d H:i:s") ,
    'updated_at' => date("Y-m-d H:i:s"),
]);

If it's successful, you can already access the newly inserted id like this: $detail->id

Upvotes: 1

Related Questions