dongtangjie0495 2018-04-28 05:11
浏览 12
已采纳

laravel auto hard delete

I have methods where i can soft delete my model, restore them and hard delete (wipe from database) theme,

So far everything is ok, what I want in additional to that is to hard delete after 30 days passed from soft delete info, so in that way even if admin forget to hard delete models it will delete automatically after 30 days.

Here is my codes:

soft delete

public function destroy($id)
    {
        $user = User::findOrFail($id);
        $user->delete();
        Mail::to($user->email)->send(new adminsoftdeleteduser($user));
        return redirect()->route('users.index')->with('success', 'User successfully deleted.');
    }

restore

public function restore($id)
    {
        $user = User::onlyTrashed()->where('id', $id)->restore();
        // Mail::to($user->email)->send(new adminrestoreduser($user));
        return redirect()->route('users.index')->with('success', 'User successfully restored.');
    }

hard delete

public function forcedelete($id)
    {
        $user = User::where('id', $id)->forcedelete();
        Storage::delete($user->image);
        return redirect()->route('users.index')->with('success', 'User Permanently deleted.');
    }

Question

  1. what should i add to my hard delete function in order to delete my model after 30 days of deleted_at column data?

Update

I've tried schedule way and as i cannot use cron job to test it so i used php artisan schedule:run and here is the result I've got:

screen1

  • 写回答

1条回答 默认 最新

  • dongshun1884 2018-04-28 05:32
    关注

    Use the Task Scheduler to automatically run a command:

    protected function schedule(Schedule $schedule)
    {
        $schedule->call(function () {
            $users = User::whereNotNull('deleted_at')->where(
                'deleted_at', '<=', now()->subDays(30)->toDateTimeString()
            )->get();
    
            $users->each->forceDelete();
        })->daily();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有没有可以帮我搞一个微信建群链接,包括群名称和群资料群头像那种,不会让你白忙
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题