mafortis
mafortis

Reputation: 7128

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

Upvotes: 0

Views: 451

Answers (2)

Sapna Bhayal
Sapna Bhayal

Reputation: 802

In controller on the basis of created date set a new variable i.e. $isNew

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

And pass to the view. In view just check that

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

or you can do direct comparison in view

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

//place your HTML here

@endif

Upvotes: 1

Quezler
Quezler

Reputation: 2435

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.

Upvotes: 1

Related Questions