adamnet's avatar

Deleting rows massively using DB facade

I would like to delete massively records using the DB facade with a WHERE clause in a classic delete query. I do not want to use the Model Eloquent methods. A possible way to do it is below

DB::delete('DELETE FROM users WHERE id = ?', [$id]);
          echo ("User Record deleted successfully.");
          return redirect()->route('users.index');

Question: Is it possible instead of using the primary key $id to use another field which is not the primary key?

0 likes
4 replies
martinbean's avatar

Is it possible instead of using the primary key $id to use another field which is not the primary key?

@adamnet Yes? Just specify it?

DB::delete('DELETE FROM users WHERE some_other_column = ?', [$value]);

Alternatively, you can still use the query builder:

DB::table('users')->where('some_other_column', '=', $value)->delete();
imranbru's avatar

If you want to stick to your raw SQL string approach, you just change the column name in the query:

DB::delete('DELETE FROM users WHERE account_status = ?', [$status]);

or you can follow this also

DB::table('users')->where('account_status', $status)->delete();
martinbean's avatar

@imranbru You’ve pretty much just repeated my comment and examples, and added nothing extra? 🤷‍♂️

jlrdw's avatar

Can you show the fields /s you want to use?

Edit:

I suggest backing up the database first, otherwise you could loose data.

Please or to participate in this conversation.