One way to simplify the code and avoid repeating the same logic for each table is by using a dynamic approach. You can create a method that accepts the table name as a parameter and checks if the user is referenced in any of the specified columns. Here's an example implementation:
public function isUserReferenced($tableName)
{
$columns = ['created_by', 'modified_by', 'deleted_by'];
foreach ($columns as $column) {
$count = $this->hasMany($tableName, $column, 'id')->count();
if ($count > 0) {
return true;
}
}
return false;
}
public function in_use()
{
$tables = ['Operator', 'Source', 'UnitType'];
foreach ($tables as $table) {
if ($this->isUserReferenced($table)) {
return true;
}
}
return false;
}
In this solution, the isUserReferenced method accepts the table name as a parameter and iterates over the specified columns to check if the user is referenced in any of them. The in_use method then iterates over the tables array and calls isUserReferenced for each table. If any of the tables reference the user, it returns true; otherwise, it returns false.
This way, you can easily add or remove tables from the $tables array without having to modify the code for each table individually.