Is there a way to automatically cast a model's attribute whose type is time
in the same way we do with date
or datetime
?
I know about mutators, but I wonder if it can be done in a cleaner way, like using $casts
property.
Accessors and mutators allow you to format Eloquent attributes when retrieving them from a model or setting their value. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.
Casting a value means changing it to (or ensuring it is already) a particular type. Some types you might be familiar with are Integer or Boolean . Simply put, type casting is a method of changing an entity from one data type to another.
Laravel model attributes are basically representing the database fields for the given model.
Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.
As of Laravel 5.6, it is possible to use $casts
to specify custom formats for dates & times. (relevant docs)
You'd want something like this:
protected $casts = [
'created_at' => 'datetime:H:i',
];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With