Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Model - cast of time

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.

like image 899
juniorgarcia Avatar asked Jul 06 '18 23:07

juniorgarcia


People also ask

What is accessors and mutators in Laravel?

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.

What is casts in Laravel 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.

What is Laravel model attributes?

Laravel model attributes are basically representing the database fields for the given model.

What is Laravel eloquent?

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.


1 Answers

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',
];
like image 91
Sara Avatar answered Sep 27 '22 18:09

Sara