Laravel 用碳计时

Laravel timing with carbon

我尝试根据产品发布时间在我的应用中显示 new label

逻辑

  1. 显示自产品发布时间 created_at20 days 之后的新标签。

代码

这是我目前所做的,但不确定。

$new = Product::where('created_at', '=<', Carbon::now()->subDays(30));

screenshot

此标签只能在前 20 天显示。

问题

  1. 如何在我的 blade 中为 $new 创建 if statement? (我的意思是我创建了 @if($new)...@endif 它不起作用)
  2. 我的代码正确吗?

更新

my page controller

$products = DB::table('products')
              ->join('page-views','products.id','=','page-views.visitable_id')
              ->select(DB::raw('count(visitable_id) as count'),'products.*')
              ->groupBy('id')
              ->orderBy('count','desc')
              ->having('count', '>=', 100)
              ->get();

PS:我必须添加我在 Base on Quezler answer 下面添加代码到我的模型,即使在我的正常 collection 例如 $products = Product::all(); 给出同样的错误。

error

Undefined property: stdClass::$new 

model

public function getNewAttribute(): boolean
    {
        return (clone $this->created_at)->addDays(20)->greaterThanOrEqualTo(Carbon::now());
    }

将此添加到您的 Product 模型中:

public function getNewAttribute(): bool
{
    return (clone $this->created_at)->addDays(20)->greaterThanOrEqualTo(Carbon::now());
}

然后在 blade 中你可以在处理产品的同时@if($product->new)

在控制器中根据创建日期设置一个新变量即 $isNew

$created = new Carbon($products->created_at);
$now = Carbon::now();
$isNew = ($created->diff($now)->days < 20)? True: FALSE;

并传递给视图。在视图中,只需检查

@if($isNew)?.....@endif

或者你可以在视图中直接比较

@if(\Carbon\Carbon::now()->diffInDays($product->created_at, false) < 20)

//把你的HTML放在这里

@endif