本文目录导读:

在 Laravel 中恢复软删除的数据有几种方法,我来详细介绍:
基础恢复方法
使用 restore() 方法恢复单个模型
use App\Models\User; // 找到软删除的数据并恢复 $user = User::withTrashed()->find($id); $user->restore();
恢复多个软删除的数据
// 恢复所有软删除的用户
User::onlyTrashed()->restore();
// 恢复指定条件的软删除数据
User::onlyTrashed()
->where('deleted_at', '>=', now()->subDays(7))
->restore();
在 Service 或 Repository 层封装
<?php
namespace App\Services;
use App\Models\User;
use Illuminate\Support\Facades\DB;
class UserService
{
/**
* 恢复单个用户
*/
public function restoreUser(int $id): bool
{
try {
DB::beginTransaction();
$user = User::withTrashed()->findOrFail($id);
$user->restore();
DB::commit();
return true;
} catch (\Exception $e) {
DB::rollBack();
throw $e;
}
}
/**
* 批量恢复用户
*/
public function restoreMultipleUsers(array $ids): int
{
return User::withTrashed()
->whereIn('id', $ids)
->restore();
}
/**
* 恢复指定时间前的数据
*/
public function restoreBeforeDate(string $date): int
{
return User::withTrashed()
->where('deleted_at', '<', $date)
->restore();
}
}
在 Controller 中使用
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Services\UserService;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
class UserController extends Controller
{
protected $userService;
public function __construct(UserService $userService)
{
$this->userService = $userService;
}
/**
* 恢复单个用户
*/
public function restore(Request $request, $id): JsonResponse
{
try {
$result = $this->userService->restoreUser($id);
return response()->json([
'success' => true,
'message' => '用户恢复成功',
'data' => $result
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => '恢复失败:' . $e->getMessage()
], 500);
}
}
/**
* 批量恢复用户
*/
public function batchRestore(Request $request): JsonResponse
{
$request->validate([
'ids' => 'required|array',
'ids.*' => 'integer'
]);
try {
$count = $this->userService->restoreMultipleUsers($request->ids);
return response()->json([
'success' => true,
'message' => "成功恢复 {$count} 个用户"
]);
} catch (\Exception $e) {
return response()->json([
'success' => false,
'message' => '批量恢复失败:' . $e->getMessage()
], 500);
}
}
}
带关联数据的恢复
class UserService
{
/**
* 恢复用户及其关联数据(带关联的软删除)
*/
public function restoreUserWithRelations(int $id): bool
{
$user = User::withTrashed()
->with(['posts' => function ($query) {
$query->withTrashed();
}])
->findOrFail($id);
// 恢复关联数据(如果关联模型也使用了软删除)
foreach ($user->posts as $post) {
if ($post->trashed()) {
$post->restore();
}
}
// 恢复主模型
$user->restore();
return true;
}
}
使用请求验证和路由
// routes/api.php
Route::post('/users/{id}/restore', [UserController::class, 'restore']);
Route::post('/users/batch-restore', [UserController::class, 'batchRestore']);
前端使用方法
// 使用 Axios 调用
async function restoreUser(userId) {
try {
const response = await axios.post(`/api/users/${userId}/restore`);
console.log('恢复成功:', response.data);
return response.data;
} catch (error) {
console.error('恢复失败:', error.response.data);
throw error;
}
}
async function batchRestoreUsers(userIds) {
try {
const response = await axios.post('/api/users/batch-restore', {
ids: userIds
});
console.log('批量恢复成功:', response.data);
return response.data;
} catch (error) {
console.error('批量恢复失败:', error.response.data);
throw error;
}
}
高级技巧
条件软删除模型
class User extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
// 获取还包含已删除记录的数据
public function scopeWithDeleted($query)
{
return $query->withTrashed();
}
// 获取仅软删除的数据
public function scopeOnlyDeleted($query)
{
return $query->onlyTrashed();
}
}
事件监听
class User extends Model
{
use SoftDeletes;
protected static function booted()
{
static::restoring(function ($user) {
// 恢复前操作
Log::info('用户即将被恢复', ['id' => $user->id]);
});
static::restored(function ($user) {
// 恢复后操作
Log::info('用户已恢复', ['id' => $user->id]);
});
}
}
注意事项
- 权限检查:恢复操作前要检查用户是否有权限
- 事务处理:涉及多个操作时使用事务
- 日志记录:记录恢复操作日志
- 关联检查:恢复前检查关联数据的状态
- 唯一性验证:恢复后可能需要验证唯一字段不冲突
public function restoreUser(int $id): bool
{
return DB::transaction(function () use ($id) {
$user = User::withTrashed()->findOrFail($id);
// 权限检查
if (!auth()->user()->can('restore', $user)) {
abort(403, '无权恢复该用户');
}
// 检查唯一性
$emailExists = User::where('email', $user->email)
->where('id', '!=', $id)
->exists();
if ($emailExists) {
throw new \Exception('邮箱已被其他用户使用');
}
$user->restore();
// 记录日志
activity()
->performedOn($user)
->log('用户已恢复');
return true;
});
}
这样就能安全、完整地实现软删除数据的恢复功能了。