我收到对成员函数diffForHumans字符串错误的调用

时间:2018-11-28 09:31:52

标签: laravel php-carbon

这是我的方法的样子:

public function show(Game $game)
{
    $discussion = DB::table('chatter_post')->whereId($game->chatter_post_id)->first();

    $chatter_post = DB::table('chatter_post')->where('chatter_discussion_id', $discussion->chatter_discussion_id)
                                             ->whereNotIn('id', [$game->chatter_post_id])->get();

                                             dd($chatter_post);
    return view('games.games', ['game' => $game, 'discussions' => $chatter_post]);
}

当我在dd($ chatter_post)中转储并死亡时,我可以看到所有数据:

0 => {#861 ▼
  +"id": 20
  +"chatter_discussion_id": 25
  +"user_id": 1
  +"body": "<p>Everything will be placed here</p>"
  +"created_at": "2018-11-28 08:10:39"
  +"updated_at": "2018-11-28 08:10:39"
  +"markdown": 0
  +"locked": 0
  +"deleted_at": null
}

但是在前端,当我尝试使用diffForHumans时,我看到此错误:

Call to a member function diffForHumans() on string 

这是我的前端的样子:

@foreach($discussions as $discussion)       
    <div class="flex">
        <div class="avatar"></div>
        <blockquote class="main_content">
            <p class="author_created">Author Name {{$discussion->created_at->diffForHumans()}} </p>
            <div>{!!$discussion->body!!}</div>
        </blockquote>
    </div>
@endforeach

为什么在调用getDIffForHumans时出现错误?

1 个答案:

答案 0 :(得分:2)

您的日期不是Carbon的实例,因此请解析它,然后执行diff像这样:

{{ \Carbon\Carbon::parse($discussion->created_at)->diffForHumans() }}