user1783675
user1783675

Reputation: 356

Retrieve from database, calculate and post to the view

I would like to calculate the difference between two dates and post the result to the view. The table contains the following rows:

Id, AuthorId, duedate,body

I know how to calculate the difference between two dates, but this is for a single row. Now, I'm pulling multiple rows from the database, and according to laravel I'm not supposed to perform any calculation in the view.

Below is from the controller:

 public function index()
{
    //

    $posts = Post::all();
    $to = \Carbon\Carbon::now();
    $from = \Carbon\Carbon::createFromFormat('Y-m-d H:s:i', '2015-5-6 9:30:34');

    $diff_in_days = $to->diffInDays($from);

    return view('blog.index',['posts'=>$posts,'diffdays'=>$diff_in_days]);
}

I just used a dummy date for the $from variable. It's supposed to be replaced with the due datedate value from the database. I am not sure how to approach so I can perform the calculation in the controller before passing it to the view.
I'm still learning laravel, any help will be great.

Upvotes: 2

Views: 87

Answers (2)

Levente Otta
Levente Otta

Reputation: 795

If duedate is astandard dateTime column and if you've added duedate to the $dates array in your model:

protected $dates = ['duedate'];

Now duedate is casted to timestamp so you can use Carbon\Carbon methods on this variable.

Let see what you need in controller:

public function index()
{
    $posts = Post::all();
    return view('blog.index', compact('posts'));
}

Then you can just do this in a view:

@foreach ($posts as $post)
    {{ $post->duedate->diffForHumans() }}
@endforeach

Tested in artisan tinker:

Days:

>>> $now = Carbon\Carbon::now()->addWeek()
=> Carbon\Carbon @1520345864 {#814
     date: 2018-03-06 15:17:44.571132 Europe/Budapest (+01:00),
   }
>>> $now->diffForHumans();
=> "6 days from now"

Hours:

>>> $now = Carbon\Carbon::now()->addDay()
=> Carbon\Carbon @1519827379 {#811
     date: 2018-02-28 15:16:19.447731 Europe/Budapest (+01:00),
   }
>>> $now->diffForHumans();
=> "23 hours from now"

Upvotes: 2

Alexey Mezenin
Alexey Mezenin

Reputation: 163838

If duedate is astandard dateTime column and if you've added duedate to the $dates array:

protected $dates = ['duedate', 'created_at', 'updated_at'];

If it's not, create an accessor for the date to convert a custom date string to a Carbon instance.

Then you can just do this in a view:

@foreach ($posts as $post)
    {{ $post->duedate->diffInDays() }}
@endforeach

Upvotes: 2

Related Questions