为什么当我添加$date->addDays(5)时,它没有在我的刀片上显示任何东西?这是我的主计长:
use Carbon\Carbon;
...
public function index(){
$date = Carbon::now();
$date->addDays(5);
$date->format("Y-m-d");
$posts = Post::where('status','=', 1)->whereDate('created_at','=', $date)->get();
return view('home', compact('date', $date))->with('posts', $posts);
}
...这是我的home.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">All posts
<a href="/posts/create" class="btn btn-primary" style="margin-left: 70%">New post +</a></div>
<hr>
<div class="card-body">
@foreach($posts as $post)
@if($post->status == 1)
<small style="color:red">PREMIUM POST</small>
<hr>
@endif
<h2>{{$post->name}}</h2><br>
<medium>{{$post->body}}</medium>
<hr style="border: 1.5px solid grey">
@endforeach
<small><?php echo now() ?></small>
</div>
</div>
</div>
</div>
</div>
@endsection这个问题的解决办法是什么?在我添加$date->addDays(5);之后,它没有显示任何东西在我的刀片中
编辑:我只是需要我的帖子在5天内都是可见的,而在那之后就没有了。仅此而已,也许是addDays();的错误,因为如果我删除它,我的刀片现在显示给我的帖子,但只为今天。
发布于 2020-01-12 15:23:19
created_at是由current_timestamp创建的,如果您使用addDays(5),将从特性中获取帖子。那怎么可能。
老实说,您可以添加名为expired_date的字段,与此字段相比将非常容易。
使用laravel迁移添加一个字段,如
$table->date('expired_date');创建帖子后,需要使用expired_date设置Carbon::now()->addDays(5);
并过滤超过今天的过期日期。
public function index(){
$date = Carbon::now();
$date->addDays(5);
$posts = Post::where('status','=', 1)->whereDate('created_at','>=', $date)->get();
return view('home', compact('date', $date))->with('posts', $posts);
}如果您的status字段只是为了区分过期或未过期,我认为您不需要这个字段。
但是,如果您确实需要此字段来维护过期状态。
您需要每天更新它,尝试使用任务调度
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
Post::where('expired_date', '<=', \Carbon\Carbon::today())->update(['status' => 0]);
})->daily();
}发布于 2022-03-15 05:14:29
$date= Carbon::now()->addDays(5);
$posts = Post::where('status','=', 1)->whereDate('created_at','=', $date)->get();
return view('home', compact('date', $date))->with('posts', $posts);https://stackoverflow.com/questions/59705101
复制相似问题