have my table set up with a timestamp fields for created and updated at fields.
In my model I then do this:
protected $dates = ['created_at', 'updated_at'];
But when calling the date:
$p->created_at->diffForHumans()
I get
Call to a member function diffForHumans() on string
I'm pretty sure that should work. I have used the same many times before on different models etc but this just won't work.
By default, Eloquent will convert the created_at and updated_at columns to instances of Carbon, which provides an assortment of helpful methods, and extends the native PHP DateTime class.
Read: https://laravel.com/docs/5.1/eloquent-mutators#date-mutators
Just check your composer.json file for nesbot/carbon package. In case if you don't have you can install it by typing
composer require nesbot/carbon
Alternative Solution is,
You could use Carbon::parse() to create object on the fly.
Carbon::parse($p->created_at)->diffForHumans();
The Laravel diffForHumans()
functions as I have used in version 5.2, only works when you are using on created_at
and updated_at
, otherwise it will bring you the Call to a member function diffForHumans() on string
error. even though you have used the created_at
and updated_at
, just be sure that on your migrations, you haven't used:
$table->timestamp('created_at');
$table->timestamp('updated_at');
But you have used
$table->timestamps();
There is a difference according to laravel
But just incase for some reason you wanted to use the diffForHumans()
function for a column that is neither created_at
and updated_at
, For instance expired_at
, Use Carbon
What I can say in summary is that:
Addon
in your laravel project folder e.g test-laravel
Carbon.php
.Carbon.php
file, enter:namespace Carbon;
class Carbon extends \DateTime{
//
}
Then go to your controller e.g ProductController.php
and add the Carbon namespace to the file:
namespace Addon;
namespace App\Http\Controllers;
use Carbon\Carbon;
use ...
class ProductController extends Controller{
$expire_date_string = '2016-07-27 12:45:32';
// Parse date with carbon
$carbonated_date = Carbon::parse($expire_date_string);
// Assuming today was 2016-07-27 12:45:32
$diff_date = $carbonated_date->diffForHumans(Carbon::now());
echo $diff_date; // prints "1 month after"
}
For more information about the Carbon Controllers, visit: http://carbon.nesbot.com/docs/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With