Reputation: 7128
I try to show new label
in my app depending on products publishing time.
created_at
till 20
days
after.this is what I did so far, but not sure about it.
$new = Product::where('created_at', '=<', Carbon::now()->subDays(30));
screenshot
this label must be shown only first 20 days.
if statement
in my blade for $new
? (i mean i created @if($new)...@endif
it doesn't work)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
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
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