Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel date not allowing me to use diffForHumans

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.

like image 657
Lovelock Avatar asked Nov 28 '22 14:11

Lovelock


2 Answers

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();
like image 165
Roshimon Avatar answered Dec 23 '22 08:12

Roshimon


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:

  1. You first create a new folder may be called Addon in your laravel project folder e.g test-laravel
  2. Then inside the folder, you create a new file called Carbon.php.
  3. Inside the 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/

like image 34
Pyr James Avatar answered Dec 23 '22 07:12

Pyr James