Reputation: 191
I'm using Eloquent in a project, basically I have a Author model, that has name, email, etc.
I have $author->created_at,
and $author->name,
etc.
What I want, is more fields in the object that are always there, for example: $author->created_at_formatted,
which would basically be date(format, created_at)
Any ideas or tips on how I can do this within the class? Thanks.
Upvotes: 1
Views: 1483
Reputation: 15653
You need to understand how eloquent works and what its main purpose is.
It is simply just a way to easily interact with a database table through an object (It is an Object-relational mapper i.e. it maps a relational database table to an object)
If you want it to have another field, you would have to add that field to your database table.
If however that other field is part of ANOTHER table, you can use the join() query method. The fields from both tables will be added. If for whatever reason you cannot modify your author table, you could create another table with the fields you want and then do a join.
If you want more help doing a join, let me know and I'll add the code here.
Upvotes: 0
Reputation: 18665
The model itself should not be responsible for making the data "pretty" for things like views. Many people would opt to do this in the controller or even the view. I recommend you look into "presenters" and how they are used to transform and manipulate the data for views.
There are existing presenter packages available for Laravel 4 which you can start using right away (and I recommend that you do).
Upvotes: 1
Reputation: 478
I don't know if there is a way to create your own automatically populated columns, but if a "created_at_formatted" column is all you need, you can just add the following to your model to change the format of the created_at and updated_at columns:
public function freshTimestamp()
{
// Your custom timestamp format
return date("Y-m-d H:i:s");
}
Upvotes: 0