Search code examples
laravelphp-carbon

Laravel timing with carbon


I try to show new label in my app depending on products publishing time.

Logic

  1. Show label new since product publishing time created_at till 20 days after.

Code

this is what I did so far, but not sure about it.

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

screenshot

screenone

this label must be shown only first 20 days.

Question

  1. How do I make if statement in my blade for $new? (i mean i created @if($new)...@endif it doesn't work)
  2. Is my code correct?

UPDATE

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: I have to add I added code below Base on Quezler answer to my model even on my normal collection such as $products = Product::all(); gives same error.

error

Undefined property: stdClass::$new 

model

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

Solution

  • Add this to your Product model:

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

    Then in blade you can do @if($product->new) while handeling products.