Laravel-过期的碳

问题描述 投票:0回答:1

所以在这个项目中,我必须让帖子在7天后过期。我的HomeController中有此代码,现在它显示了我今天在首页上发布的所有帖子:

...
public function index()
    {

        $date = Carbon::now();
        $date->format("Y-m-d");
        $posts = Post::where('status','=', 1)->whereDate('created_at','=', $date)->get();
        return view('home', compact('date', $date))->with('posts', $posts);
    }
...

所以它向我显示了今天状态为1的所有帖子,没关系。但是我需要告诉我,帖子不仅要发布一天,而且要发布7天,过期后需要自动删除。我该如何解决?请帮忙!谢谢!

编辑

我尝试过:

...
public function index()
    {

        $current = Carbon::now();
        $date = $current->addDays(7);
        $date->format("Y-m-d");
        $posts = Post::where('status','=', 1)->whereDate('created_at','=', $date)->get();
        return view('home', compact('date', $date))->with('posts', $posts);
    }
...

但什么也没发生。

laravel php-carbon
1个回答
1
投票

使用Carbon,您可以像这样轻松地减去天数:

$posts = Post::where('status', 1)
           ->where('created_at', '>', Carbon::now()->addDays(7))
           ->get();

foreach($posts as $post) {
    $post->delete();
}

您基本上是在比较当前日期,并从现在开始删除7天。之后,您将获得一个帖子集并删除所有内容。

您可能希望在后台构建删除逻辑,以便系统每天检查是否需要删除它。为此,您需要创建一个CronjobTask

例如,您可以轻松地创建类似这样的内容:

$schedule->job(new PostRemoveProcess, 'postsremove')->everyWeek();

检查有关此的documentation,它解释得非常好。

© www.soinside.com 2019 - 2024. All rights reserved.