In Laravel, when you use the $casts property with 'datetime:Y-m-d', it is intended to format the date when it is serialized, such as when converting a model to an array or JSON. However, when you access the attribute directly, it will still return a Carbon instance, which is why you're seeing the full ISO string.
To ensure that the birth_date is always formatted as YYYY-MM-DD when accessed, you can define an accessor in your model. Here's how you can do it:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Carbon;
class YourModel extends Model
{
protected $casts = [
'birth_date' => 'date', // Use 'date' to cast it to a Carbon instance
];
// Accessor to format the date
public function getBirthDateAttribute($value)
{
return Carbon::parse($value)->format('Y-m-d');
}
}
With this accessor, whenever you access the birth_date attribute, it will be formatted as YYYY-MM-DD. The date cast ensures that the attribute is treated as a date, but the accessor customizes the output format.
Remember, the $dateFormat property is used for formatting dates when saving to the database, not when retrieving them. So, it doesn't affect how dates are formatted when accessed.