skip to Main Content

I want to remove ‘new’ label on the post title for those posted more than 30days ago I tried this in view but not working

@foreach ($post as $p)
   @if(DB::table('post')->whereRaw('DATEDIFF(created_at, now()) > 30')->get())
    emove label goes here ...
   @endif
@endforeach

note my label is a gif image so it found in the asset folder

2

Answers


  1. Better solution is to use accessor.
    Ex. your model is Post::class, then add method:

    use IlluminateDatabaseEloquentCastsAttribute;
    use CarbonCarbon; // not sure need this, tt rm
    ...
    protected $dates = ['created_at'];
    ...
    
    // Laravel 9+ version:
    
    protected function hasNewLabel(): Attribute
    {
        return Attribute::make(
            get: fn () => $this->attributes['created_at']->gt(now()->subDays(30)->endOfDay());
        );
    }
    
    // Laravel 8 version:
    
    protected function getHasNewLabelAttribute()
    {
        return $this->attributes['created_at']->gt(now()->subDays(30)->endOfDay());
    }
    
    

    then in blade template using like this

    @foreach ($posts as $post)
       ...
       @if($post->has_new_label) // !$post->has_new_label if not, and smht inside
        // label html goes here
       @endif
       ...
    @endforeach
    
    Login or Signup to reply.
  2. You can achieve this in pure PHP or by using accessors. For example:

     @php
     $date1=date_create('2023-04-01 12:53:00'); //created_at data. Don't forget to replace the date with your created_at value. Ex: $p->created_at
     $date2=date_create(date('Y-m-d h:m:s')); //date now
    
     
      $diff=date_diff($date1,$date2); // gets the difference between two dates
      $diff=$diff->format("%a"); // format difference 
      if($diff > 30){
        echo "Remove label"; //More than 30 days
      }else{
        echo "Less than 30 days";  //Less than 30 days 
      }
    

    @endphp

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search