Laravel-到期职位的碳

Laravel-到期职位的碳,laravel,php-carbon,Laravel,Php Carbon,所以在这个项目中,我必须让帖子在七天后过期。我的HomeController中有此代码,现在它显示了我今天在主页上发表的所有帖子: ... public function index() { $date = Carbon::now(); $date->format("Y-m-d"); $posts = Post::where('status','=', 1)->whereDate('created_at','=', $date

所以在这个项目中,我必须让帖子在七天后过期。我的
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的帖子,没关系。但我需要告诉我,帖子不仅要持续一天,还要持续七天,过期后需要自动删除。我怎样才能解决这个问题?请帮忙!谢谢大家!

编辑

我试过:

...
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);
    }
...

但是什么也没发生。

使用碳,你可以很容易地减去这样的天数:

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

foreach($posts as $post) {
    $post->delete();
}
您基本上是比较当前日期,并从现在起删除7天。 之后,您将获得一个posts集合并删除所有内容

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

例如,您可以轻松创建以下内容:

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

查看关于这一点的文档,它解释得非常好。

但我不想从现在起删除7天。我想做添加7天到我的帖子,它需要显示7天,然后做自动删除。由于我当前的代码帖子只在创建日显示,我需要它显示7天,你明白吗?需要在后台完成删除过程吗?好的,我添加了你的代码
Carbon::now()->addDays(7)
,但是现在我的主页上没有显示任何内容。是的,因此不会发生错误,运行函数并删除模型。我更新了我的答案如果你想在后台运行cronjob的逻辑,我不是cronjob方面的专家,所以你应该仔细阅读文档并尝试一下:)我将我电脑上的日期和时间更新到2020/01/19,看看它是否会在7天后删除我的帖子,但什么都没有发生。我将尝试这项任务。非常感谢。