Laravel how many rows inserted in an insert query?

Viewed 1313

I have this query eloquent in Laravel, I was curious to know. If there is a way to know how many records inserted or how many records ignored to the table?

DB::table('mytable')->insertOrIgnore($data)

Note: One of the manual ways can be, counting records of table before and after process. but this has performance effect, if there be any better way achieving this.

1 Answers

The function insertOrIgnore() returns the affected rows.

/**
 * Insert a new record into the database while ignoring errors.
 *
 * @param  array  $values
 * @return int
 */
public function insertOrIgnore(array $values) {

So you can simply use the returned value and compare it to what was expected to be inserted:

$affected = DB::table('mytable')->insertOrIgnore($data);
$ignored = count($data) - $affected;
Related