How to get last inserted id in Laravel 5.8?

Posted by LaravelIndia - 1 year ago

Example 1: Using save()

public function craeteNewUser(){
    $user_data =new User();
    $user_data->name = "john25";
    $user_data->email = "[email protected]";
    $user_data->save();
    return $user->id;
}

Example 2: Using create()

public function craeteNewUser(){
    $input = ['name' => 'John Praksha', 'email'=>'[email protected]'];
    $user = User::create($input);
    return $user->id;
}

Example 3: Using insertGetId()

public function craeteNewUser(){
    $id = DB::table('users')
            ->insertGetId(
                ['name' => 'John Dave', 'email'=>'[email protected]']
            );
    return $id;
}