Search code examples
laravelphp-carbon

I am receiving call to a member function diffForHumans string error


This is what my method looks like:

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]);
}

I can see all the data when I dump and die in 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
}

But in the front-end, when I try to user diffForHumans I see this error:

Call to a member function diffForHumans() on string 

This is how my front-end looks like:

@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

Why do I get the error when I call getDIffForHumans?


Solution

  • Your date isn't an instance of Carbon, therefore parse it and then perform the diff like:

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