Support the ongoing development of Laravel.io →
Requests Eloquent Views
Last updated 2 years ago.
0

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.

Last updated 9 years ago.
0

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:

  • {{ $project->rightNow }}, which understandably returns nothing
  • {{ $rightNow}}, which returns a calculated date time left, but only for one of them

I'm not sure how to pass the calculated result from the controller into the view for each individual item. Any tips?

Last updated 9 years ago.
0

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 }}

Last updated 9 years ago.
0

Thank you, @rsands2801, that worked!

0

Sign in to participate in this thread!

Eventy

Your banner here too?

avizuber avizuber Joined 23 Apr 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.