Automatically formatting all created_at and updated_at dates in blade views
Hi,
Is there's a way to automatically apply a Carbon formatting method to all created_at and updated_at models dates when we use these attributes in blade views ?
For ex., in a blade view, when I write :
$post->created_at
I'd like something like "Fri 12 May 2023 19:05:50" to be print, instead of "2023-05-12 19:05:50".
Yes, you can create a custom Blade directive to format all created_at and updated_at dates in your Blade views. Here's an example:
Create a new Blade directive in your AppServiceProvider:
use Illuminate\Support\Facades\Blade;
use Carbon\Carbon;
public function boot()
{
Blade::directive('datetime', function ($expression) {
return "<?php echo Carbon\Carbon::parse($expression)->format('D d M Y H:i:s'); ?>";
});
}
Use the datetime directive in your Blade views to format created_at and updated_at dates:
{{ $post->created_at->datetime() }}
This will output the date in the format you specified: "Fri 12 May 2023 19:05:50".
@dacfabre Thanks for your (human) answer !
But I thought that casting will affect also dates storing in database. No ?
I just want to format these properties when displaying them in blade views.
<?php
namespace App\Traits;
trait FormattedDate
{
public function getFormattedCreatedAtAttribute()
{
return $created_at->format('D d M Y H:i:s');
}
public function getFormattedUpdatedAtAttribute()
{
return $updated_at->format('D d M Y H:i:s');
}
}
<?php
namespace App\Models;
use App\Traits\FormattedDate;
class ModelA extends Model
{
use FormattedDate;
<?php
namespace App\Models;
use App\Traits\FormattedDate;
class ModelB extends Model
{
use FormattedDate;
<?php
namespace App\Traits;
trait FormatDate
{
public function formatDate(string $attribute)
{
return $this->{$attribute}->format('D d M Y H:i:s');
}
}