The most straightforward answer would be to convert date string to Carbon instance right there in the loop:
foreach ($projects as $project)
{
$rightNow = Carbon::now()->diffForHumans(new Carbon($project->endDay));
}
But it's better to mark endDay
as date in your Project
model. See docs on how to do it. Then $project->endDay
will become an instance of Carbon class, and your foreach loop will work as is.
Awesome, thank you so much @Xum. I added endDay as a Carbon instance in my Project model and sure enough the calculation works.
My last remaining issue is that all of the list items in index.view.php are getting the same calculation back.
I tried:
I'm not sure how to pass the calculated result from the controller into the view for each individual item. Any tips?
You need to inject it back into the projects.
public function index()
{
$projects = Project::owned()->get();
foreach ($projects as $key => $loop)
{
$loop->rightNow = Carbon::now()->diffForHumans(new Carbon($loop->endDay));
}
return view('projects.index', compact('projects'));
}
Then in your view you can output it as normal in the foreach loop: {{ $project->rightNow }}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community