Saturday, December 31, 2016

Laravel insert ignore check if inserted (affected rows for insert ignore)

Halo guys!
if you break your head for finding solution to check if row is inserted here is the way

$query = "INSERT INTO table (id) VALUES (?)";
    try {
        DB::insert($query, array($value));
        return 1;
    } catch (\Exception $e) {
        return 0;
    }

The solution is simle - not use insert ignore. So we are catching exception instead of fatal erroring and know if it did or not.
You can even do query builder insert instead of raw query.

2 comments:

  1. What if I want to insert thousand rows?

    ReplyDelete
    Replies
    1. run this thousand times

      or you can preclean your data.
      Select all rows and compare with your data you want to insert and make up clean data and then using batch insert insert in 1 time. But htat's only good if you have small amount of data in table or with using condition.

      Delete