5

Laravel 5.5 - Get Last Inserted ID With Example

 1 year ago
source link: https://www.laravelcode.com/post/laravel-55-get-last-inserted-id-with-example
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Laravel 5.5 - Get Last Inserted ID With Example

  1107217 views

  5 years ago

Laravel

Today, we are share with you how to get last inserted ID in laravel with 4 simple example. we have needed some it last inserted ID in laravel application. so, here we have find 4 diffrent way to get last inserted ID in laravel. you can use it and get last ID of inserted record in laravel application.

1) Using insertGetId() method

You can get last inserted ID using insertGetId() in laravel for example

$id = DB::table('users')->insertGetId(
    [ 'name' => 'first' ]
);

dd($id);
	

[ADDCODE]

2) Using lastInsertId() method

You can also get last inserted ID using lastInsertId() in laravel. You need PDO object to run this method for example

DB::table('users')->insert([
    'name' => 'TestName'
]);
$id = DB::getPdo()->lastInsertId();;
dd($id);
	
3) Using create() method.

Yes, you can also get last ID using of laravel create() method with laravel Model. this methos is return last inssert recod's object and you can get using this object last inserted ID. for example

$data = User::create(['name'=>'first']);
dd($data->id);
	
4) Using save() method.

You can also get last inserted ID using laravel save() method. if you use save() method for insert data then you can get last inserted id like that

$data = new User;
$data->name = 'Test';
$data->save();
dd($data->id);
	

We are hope this small tutorials help everyone. if you known more way to get last inserted ID in laravel so please comment bellow. Thanks..

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK