Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

pdellepiane's avatar

Soft Delete for Query Builder

Hello, I want to soft delete a record. To get the record I need to add a few joins for example:

$device_user_contact = DB::table('device_user_contact')
                ->select('device_user_contact.device_user_id','device_user_contact.contact_id')
                ->join('contacts','contacts.id','=','device_user_contact.contact_id')
                ->where('contacts.user_id',$this -> user -> id)
                ->where('device_user_contact.device_user_id',$contact -> device_user_id)
                ->whereNull('contacts.deleted_at')
                ->delete();

But it doesnt soft delete it, it ends up removing the entire record from the DB.

How do I make it work?

Thanks in advance!

0 likes
2 replies
moharrum's avatar
Level 6

You need to use update():

$device_user_contact = DB::table('device_user_contact')
                ->select('device_user_contact.device_user_id','device_user_contact.contact_id')
                ->join('contacts','contacts.id','=','device_user_contact.contact_id')
                ->where('contacts.user_id',$this -> user -> id)
                ->where('device_user_contact.device_user_id',$contact -> device_user_id)
                ->whereNull('contacts.deleted_at')
                ->update(['deleted_at' => \Carbon::now()]);
3 likes
abrookes's avatar

Updating directly in your query as @moharrum says is definitely going to be the most efficient method, but you might also want to get() the results and delete them via the model instead of the builder:

$device_user_contact = DB::table('device_user_contact')
                ->select('device_user_contact.device_user_id','device_user_contact.contact_id')
                ->join('contacts','contacts.id','=','device_user_contact.contact_id')
                ->where('contacts.user_id',$this -> user -> id)
                ->where('device_user_contact.device_user_id',$contact -> device_user_id)
                ->whereNull('contacts.deleted_at')
                ->get()
				->each( function($item){
					$item->delete();
				});

this can potentially lead to more database traffic, but doing it this way will run your laravel environment listeners and events, and you can pack some runtime logic into the each function as well if you need

Please or to participate in this conversation.