Reputation: 602
Why is it not showing me anything on my blade when I add $date->addDays(5)
?
Here is my Controller:
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);
}
...
And this is my 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
What is solution to this problem? It doesn't showing me anything in my blade after I add $date->addDays(5);
?
EDITED : I just need my posts to be visible for 5 days and after that not. That's all, maybe the mistake is with addDays();
because if i delete it my blade is now showing me posts but only for today.
Upvotes: 1
Views: 66097
Reputation: 1759
You can add with custom date format
$date = Carbon::createFromFormat('Y.m.d', $premiumDate);
$daysAdd = 2;
$date = $date->addDays($daysAdd);
dd($date);
Upvotes: 1
Reputation: 1
$date= Carbon::now()->addDays(5);
$posts = Post::where('status','=', 1)->whereDate('created_at','=', $date)->get();
return view('home', compact('date', $date))->with('posts', $posts);
Upvotes: -2
Reputation: 13394
The created_at
is created by current_timestamp
,
if you use addDays(5)
will get the posts from feature. That's impossible.
Honestly, you can add the field named expired_date
and compared with this field will be pretty easy.
use laravel migration to add a field, like
$table->date('expired_date');
And once you create the post, you need to set the expired_date with Carbon::now()->addDays(5)
;
And filter the expired date greater than today.
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);
}
If your status
field just to distinguish expired or not expired, I think you don't need this field.
However, if you really need this field to maintain the expired status.
you need to update it every day, try to use Task Scheduling
protected function schedule(Schedule $schedule)
{
$schedule->call(function () {
Post::where('expired_date', '<=', \Carbon\Carbon::today())->update(['status' => 0]);
})->daily();
}
Upvotes: 6