Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to always append attributes to Laravel Eloquent model?

Tags:

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]"          } } 
like image 796
Mustafa Dwekat Avatar asked Feb 29 '16 14:02

Mustafa Dwekat


People also ask

How do I save multiple records in Laravel eloquent?

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.

What is append in Laravel?

Appends is for when you want data that is not available in the database on your model.

What is fillable attribute in a Laravel 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.

What is serialize in Laravel?

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(


1 Answers

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]"          } } 
like image 73
Mustafa Dwekat Avatar answered Sep 23 '22 13:09

Mustafa Dwekat