It seems like the issue you're encountering is due to the fact that the published_at attribute on your $post object is being treated as a string rather than a date object. To resolve this, you need to ensure that the published_at field is cast to a date object in your Eloquent model. Here's how you can do that:
First, make sure that your Post model has the published_at field listed in the $dates property or use the $casts property to cast it as a date. This will automatically convert the string to a Carbon instance, which is Laravel's default date handling package.
Here's an example of how to do this in your Post model:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Casts\Attribute;
class Post extends Model
{
// If you're using Laravel 7 or below, use the $dates property:
protected $dates = ['published_at'];
// If you're using Laravel 8 or above, you can use the $casts property:
protected $casts = [
'published_at' => 'datetime',
];
// If you want to use a custom date format when casting, you can define a mutator:
protected function publishedAt(): Attribute
{
return new Attribute(
get: fn ($value) => $value ? Carbon\Carbon::parse($value) : null,
set: fn ($value) => $value ? Carbon\Carbon::createFromFormat('Y-m-d\TH:i', $value) : null
);
}
}
When you're saving the date to the database, you can use the createFromFormat method from the Carbon class to create a Carbon instance from the input string:
use Carbon\Carbon;
$post->published_at = Carbon::createFromFormat('Y-m-d\TH:i', $req->input('published_at'));
$post->save();
Now, when you retrieve the published_at field from the database, it will be a Carbon instance, and you can use the translatedFormat method on it:
$locale = app()->getLocale();
$format = $locale === 'it' ? 'F, Y' : 'F, Y';
echo $post->published_at->translatedFormat($format);
This should resolve the error you're seeing and allow you to format the date as needed for display in the frontend. Remember to import the Carbon class at the top of your PHP file if you're using it directly:
use Carbon\Carbon;
Make sure to adjust the date format string in createFromFormat and translatedFormat to match the format you're expecting from the input and the format you want to display, respectively.