Call to a member function diffForHumans() on null (View: C:\xampp\htdocs\project\news\resources\views\front\home.blade.php)

Viewed 1003

I have hot news button to make posts as a hot news when i make a post as a hot news it works fine but when i don't have any hot news post it will give this error .

<div class="feature_article_inner">

    <div class="tag_lg red">
        <a href="{{ url('/details') }}/{{ $hot_news['slug'] }}">Hot News</a>
    </div>


    <!-- feature_article_title -->
    <div class="feature_article_title">
        <h1><a href="{{ url('/details') }}/{{ $hot_news['slug'] }}" target="_self">{{ $hot_news['title'] }} </a></h1>
    </div>


    <!-- feature_article_date -->
    <div class="feature_article_date">
        by: <a href="{{ url('/author') }}/{{ $hot_news['creator']['id'] }}">{{ $hot_news['creator']['name'] }}</a> ,
        &nbsp;{{ $hot_news['created_at']->diffForHumans() }} </a></div>


    <div style="font-size: 9.5pt; color: black; "> Views: {{ $hot_news['view_count'] }} </div>


    <!-- feature_article_content -->
    <div class="feature_article_content">
        {{ $hot_news['short_description'] }}
    </div>


    <!-- article_social -->
    <div class="article_social">
        <span>
            <i class="fas fa-comment"></i>
            <a href="{{ url('/details') }}/{{ $hot_news['slug'] }}">
                {{ $hot_news['comments_count'] }} Comments
            </a>
        </span>
    </div>

</div>
2 Answers

The query builder return dates as strings, you need to parse before using them or you will get an error like this one PHP error.

Solution :

Because your created_at comes as a string, you will have to parse it for Carbon to work and Fix it Call to Member Function

{{\Carbon\Carbon::parse($hot_news['created_at'])->diffForHumans() }}

Even though Muhammad's answer is correct, I usually add this type of casting directly to my Model::class. This will make sure that my code of parsing the date is never duplicated. So in future if I want to change the date format, I just have to change it here and all is good to go.

use Carbon\Carbon;

public function getCreatedAtAttribute($date)
{
    return Carbon::parse($date)->diffForHumans();
}

You can study more about Laravel Accessors & Mutators here.

Related