PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, January 19, 2022

[FIXED] Laravel 5 if statement between Carbon diffForHumans and toFormattedDatesString

 January 19, 2022     laravel, laravel-5, laravel-5.1, laravel-5.2, laravel-5.3     No comments   

Issue

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 !!}


Answered By - Balraj Allam
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing