get the last inserted Id using laravel eloquent

124

get the last inserted Id using laravel eloquent -

//if you have used save method like this
$data->save();
//use this to get last row id;
$lastRowId = $data->id;

//For other insert methods get last inserted id like below
    
    //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();

laravel query builder get last insert id -

$id = DB::table('users')->insertGetId(
    ['email' => '[email protected]', 'votes' => 0]
);

laravel get ID from insert -

$data = User::create(['name'=>'first']);
dd($data->id);
	

laravel model save get id -

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

Comments

Submit
0 Comments