Year data type

Hi folks, I'm trying to retrieve data from a table where I set one of the columns to have the mysql data type to be Year(). I know Eloquent can handle this because the migration can use ->year() quite happily and it translates well into the table itself. The data then is just various years. However filament seems to think the data held in there is a Unix timestamp and I can't figure out how to retrieve the data as is and not have it be transformed into a full date some time in the early hours of 1st Jan 1970. It seems like it should be a really straightforward thing to do and yet I can't find anything online about this. On the table in the Resource I tried to force numeric() but that returns a formatted date. Obviously date() also treats it as a time stamp and I can't think of what else to try to simply retrieve the data as it's being stored in the database.
7 Replies
Matthew
Matthew18h ago
Are you casting anything in your model?
adevade
adevade18h ago
You can define the casts on the Eloquent model to get a Carbon instance from a custom format: 'year' => 'date:Y' Or you could just cast it to an integer if you don't need Carbon
Jean-Loup
Jean-LoupOP18h ago
Not particularly no. To be fair I could probably just use an integer but since the data type is available and I'm actually storing years that seems to make more sense @adevade how would I do that when defining a table column in the resource?
adevade
adevade17h ago
If you cast it to a Carbon object with date:Y, it should use the value as a year instead of a unix timestamp I believe this should work, but I have not tested unfortunately. Otherwise you could just store the year as an integer and user accessors and mutators on the model to get it in your desired format throughout your application: https://laravel.com/docs/10.x/eloquent-mutators#accessors-and-mutators
Jean-Loup
Jean-LoupOP17h ago
I'm still confused how I can cast a Carbon object. Which method do I use under TextColumn?
adevade
adevade17h ago
You should define the cast on the Eloquent model: https://laravel.com/docs/10.x/eloquent-mutators#date-casting
Jean-Loup
Jean-LoupOP17h ago
Yeah well I already had it cast as 'datetime:Y' and just changed it to 'date:Y' but in both cases it sees it as a timestamp which makes no sense so I guess I'll just use an integer... Ok so as it turns out casting to 'datetime:Y' is what was causing the issue. Remove the cast and the data displays correctly

Did you find this page helpful?