'How to show mata timestamp with laravel?
i want a meta timestamp for alle the articles when published. How do i make this automatically?
Eksempel i use this for the articles when published to show the time when a article is published and updated:
<time>{{ $post->created_at->diffForHumans() }}</time>
I want to making this one automatically:
<p class="timestamp"><time class="format-distance-to-now" itemprop="datePublished" datetime="2022-03-21T20:15:43.000Z">2022-03-21T20:15:43.000Z</time></p> </div>
Example with php (wordpress):
<time itemprop="datePublished" class="published" datetime="<?php echo get_the_time('c'); ?>" content="<?php echo get_the_time('c'); ?>">
<?php echo get_the_date(); ?>
</time>
How do i make this with laravel?
Solution 1:[1]
You could use a mutator or create another attribute on the post model. e.g.
<?php
namespace App\Models;
class Post extends Model {
public function getCreatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
}
This way when using {{ $post->created_at }} in your blade it will render 2022-12-29 or however you want to render it.
You can also set them to dates in the model instead like so
public static $dates = ['updated_at', 'created_at'];
This way you can just do {{ $post->created_at->format('Ymd') }} in the blade which imo is much nicer.
e.g.
<time itemprop="datePublished" class="published" datetime="{{ $post->created_at->format('c') }}" content="{{ $post->created_at->format('c') }}">
{{ $post->created_at->format('Ymd') }}
</time>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
