Friday, February 8, 2019

Laravel, get last insert id using Eloquent | laravel 5.2 get insert id from eloquent model | Get Last Inserted ID With Example

We have needed some it last inserted ID in Laravel application. so, here we have find 4 different way to get last inserted ID in Laravel. you can use it and get last ID of inserted record in Laravel application.
Using lastInsertId() method
DB::table('users')->insert([
    'name' => 'TestName'
]);
$id = DB::getPdo()->lastInsertId();
Using create() method
$data = User::create(['name'=>'first']);
$id = $data->id;
Using save() method
$data = new User;
$data->name = 'Test';
$data->save();
$id = $data->id;
Using insertGetId() method
$id = DB::table('users')->insertGetId([
    'name' => 'first'
]);

No comments:

Post a Comment