Hi I want to create my own timestamp which will work with carbon diffIn function my problem is getting an "Call to a member function diffInSeconds() on a non-object" even tough timestamp is made proper?.

public function up()
{
    Schema::create('global_limits', function(Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');
        $table->integer('c_limiter');
        $table->timestamp('time_comment');
        $table->timestamps('');
    });
}

Here is how I create timespam to time_comment

  $first_limit = new Limiter;
  $first_limit->c_limiter = 1;
  $first_limit->user_id = $id;
  $first_limit->time_comment = new DateTime;

  $first_limit->save();

when

$user = User::find(1)->limits;

echo $user->time_comment I get 2014-04-09 18:20:55 but when I do echo $user->time_comment->diffInSeconds(); <- get an error

Call to a member function diffInSeconds() on a non-object on proper timestamp.

Strange thing is that when I make the same thing with created_at and uptaded_at it works fine.

echo $user->created_at->diffInSeconds(); <-- works fine shows diffrence in seconds

I know that I can use updated_at for this but I want to use time_comment I have my reasons for that.

I don't want the diffForHumans because my goal is to use

    if($user->time_comment->diffInSeconds() > 500)
{do something)else {do this}
有帮助吗?

解决方案

Laravel only treats created_at, updated_at and deleted_at as Carbon instances by default. You need to add the following to your User model

public function getDates()
{
    return array('created_at', 'updated_at', 'time_comment');
}

This tells Laravel to treat the columns in the array as Carbon instances.

其他提示

$first_limit = new Limiter;
$first_limit->c_limiter = 1;
$first_limit->user_id = $id;
$first_limit->time_comment = new DateTime; ///////////////// CHANGE IT to Carbon::now()

$first_limit->save();

your sure add Carbon instance to the time_comment

As of Laravel 8 (not sure since which version this exists) you just add this to your model

protected $dates = ['time_comment'];

to get a Carbon.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top