I was wondering how to always append some data to Eloquent model without the need of asking for it for example when getting Posts form database I want to append the user info for each user as:
{ id: 1 title: "My Post Title" body: "Some text" created_at: "2-28-2016" user:{ id: 1, name: "john smith", email: "[email protected]" } }
Sometimes you might need to save multiple records at once and you can do so by using the "saveMany()" method or the "createMany()" method available to each of the Eloquent model relation. Do note that you need to have "hasMany()" relationship in order to do so.
Appends is for when you want data that is not available in the database on your model.
The fillable property is used inside the model. It takes care of defining which fields are to be considered when the user will insert or update data. Only the fields marked as fillable are used in the mass assignment. This is done to avoid mass assignment data attacks when the user sends data from the HTTP request.
October 5th, 2021. Eloquent Serialize is a Laravel package to serialize and unserialize Eloquent query builder objects. The EloquentSerialize service has two methods, serialize and unserialize . Given the following simple query, you can serialize the builder results: 1$data = \EloquentSerialize::serialize(
After some search I found that you simply need to add the attribute you wants to the $appends
array in your Eloquent Model:
protected $appends = ['user'];
Update: If the attribute exists in the database you can just use
protected $with= ['user'];
according to David Barker's comment below
Then create an Accessor as:
public function getUserAttribute() { return $this->user(); }
This way you always will have the user object for each post available as:
{ id: 1 title: "My Post Title" body: "Some text" created_at: "2-28-2016" user:{ id: 1, name: "john smith", email: "[email protected]" } }
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