80 lines
2.2 KiB
PHP
80 lines
2.2 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Actions\User;
|
||
|
|
|
||
|
|
use App\Models\User;
|
||
|
|
use Exception;
|
||
|
|
use Illuminate\Support\Facades\DB;
|
||
|
|
use Illuminate\Support\Facades\Log;
|
||
|
|
|
||
|
|
class DeleteUserAction
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* @throws Exception
|
||
|
|
*/
|
||
|
|
public function execute(User $user): bool
|
||
|
|
{
|
||
|
|
try {
|
||
|
|
DB::beginTransaction();
|
||
|
|
|
||
|
|
Log::info('DeleteUserAction: Starting user deletion', [
|
||
|
|
'user_id' => $user->id,
|
||
|
|
'user_name' => $user->name,
|
||
|
|
'planner_id' => $user->planner_id,
|
||
|
|
]);
|
||
|
|
|
||
|
|
// Check for related data
|
||
|
|
$userDishCount = $user->userDishes()->count();
|
||
|
|
$dishCount = $user->dishes()->count();
|
||
|
|
|
||
|
|
Log::info('DeleteUserAction: User relationship counts', [
|
||
|
|
'user_id' => $user->id,
|
||
|
|
'user_dishes_count' => $userDishCount,
|
||
|
|
'dishes_count' => $dishCount,
|
||
|
|
]);
|
||
|
|
|
||
|
|
// Store user info before deletion for verification
|
||
|
|
$userId = $user->id;
|
||
|
|
$userName = $user->name;
|
||
|
|
|
||
|
|
// Delete the user (cascading deletes should handle related records)
|
||
|
|
$result = $user->delete();
|
||
|
|
|
||
|
|
Log::info('DeleteUserAction: Delete result', [
|
||
|
|
'result' => $result,
|
||
|
|
'user_id' => $userId,
|
||
|
|
]);
|
||
|
|
|
||
|
|
if (! $result) {
|
||
|
|
throw new Exception('User deletion returned false');
|
||
|
|
}
|
||
|
|
|
||
|
|
// Verify the deletion actually happened
|
||
|
|
$stillExists = User::find($userId);
|
||
|
|
if ($stillExists) {
|
||
|
|
throw new Exception('User deletion did not persist to database');
|
||
|
|
}
|
||
|
|
|
||
|
|
DB::commit();
|
||
|
|
|
||
|
|
Log::info('DeleteUserAction: User successfully deleted', [
|
||
|
|
'user_id' => $userId,
|
||
|
|
'user_name' => $userName,
|
||
|
|
]);
|
||
|
|
|
||
|
|
return true;
|
||
|
|
|
||
|
|
} catch (Exception $e) {
|
||
|
|
DB::rollBack();
|
||
|
|
|
||
|
|
Log::error('DeleteUserAction: User deletion failed', [
|
||
|
|
'user_id' => $user->id,
|
||
|
|
'error' => $e->getMessage(),
|
||
|
|
'trace' => $e->getTraceAsString(),
|
||
|
|
]);
|
||
|
|
|
||
|
|
throw $e;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|