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

papa's avatar
Level 3

How to delete a records which its ID not exists in another tables ?

Hi,

I have a table of users

Users
id, first_name, last_name
1, Tom, Baar

and also I have 10 tables where all of them have a column which is the foreign_key of user_id

e.x.

Contracts
id, name, contract_manager(foreign key of users table)
1, Servers, 1

Logs
id, data, user_id(foreign key of users table)
1, data, 1

My question is how can I check if the user_id who I want to delete exists in one of the 10 tables it is associated so that I prevent the deleteion of the user ?

0 likes
4 replies
bashy's avatar

You'll just have to add queries to check if it has relations. whereDoesntHave or something.

papa's avatar
Level 3

@bashy yeah I guess something like this.

function deleteUser($id)
{
    // Here the relations to check if exists at least a record
    // of 1 of 10 Tables
}

daanb's avatar

You can create a scope in your Users model which accepts an array of tables and columns as a parameter:

Loop through the tables with a join. And return true or false, if false it's not in the other tables.

public function scopeExists($query, array $tables = ['contracts.contract_manager', 'logs.user_id']) : bool
{
     foreach($tables as $table){
            $tableColumn = explode('.', $table);
            $query->join($tableColumn[0], $tableColumn[0]}.'.'.$tableColumn[1], '=', 'users.id')
     }

     return $query->count() === 0 ? false : true;
}
shez1983's avatar

you dont have to create a custom scope... laravel has a default whereHas('relation').. although it could get annoying if you have LOTS of tables but for 2/3 this suffices..

Please or to participate in this conversation.