Search code examples
laravellaravel-5laravel-5.1laravel-5.3

Laravel 5 if statement between Carbon diffForHumans and toFormattedDatesString


I want to write an if statement to show timestamp in diffForHumans format for timestamps less than less than 5 days old and in toFormattedDatesString for anything older than that.

For example today is 31/10/17, so timestamp for 28/10/2017 should show - 3 days ago and timestamp for 20/10/2017 should show Oct 20, 2017.

What logic should I use to achieve this?


Solution

  • In your Model e.g A.php, create an accessor like this,

    public function getCreatedAtAttribute(){
        if($this->created_at->diffInDays(Carbon::now()) > 5){
           return $this->created_at->toFormattedDateString();
        }else{
           return $this->created_at->diffForHumans();
        }
    }
    

    and in your view you can access it as

    {!! $a->created_at !!}