How to call set $append attribute in manual way when need it?
I would like to know if I could actually set the $append attribute manually when i need it?
For example, in my model
$append = ['type']
public function getTypeAttribute($value) {
return .....
}
I have a resource which is sharing with other related response. I would like to control it to whether get this type attribute when return as a response. As i noticed, even i removed append, whenever i called $this->type in my resource i will still get the value.
How can i check if the attribute want to be included in the resources?
@Sinnbeck I have a case, which i am using a same resources for index() and edit(). I need this type attribute (this type is not related to database, just append by me manually) in my index() but not for the edit(). How should I remove it when I am with edit()? Or i have to create a new resource for it?
@Sinnbeck It's just simple where the resource return the attribute with type = $this->type, while actually the type here is not a database field. I just create an accessor for this type attribute and append within my model. So, whenever i query i will get this attribute, but then I would like to make it able to include or exclude when i query my result.
I think i am going to create new resource if there's no way can define in this way.
For example I use $appends (notice your error, append with an 's') to get calculated properties. As said by @sinnbeck, no need to use an appended property to access a field which is in the database.
But you say that this field is not in the database ?
class ExampleModel extends Model {
// protected $appends = [`sample`]; // --> I DONT want this because it will going to append on every query I make using this model
public function getSampleAttribute() {
...
}
}
What I wanted was to be able to only append if I needed it.
for example:
ExampleModel::withAppend('sample')->get(); // data should have a sample attribute added although withAppend does not exist.
ExampleModel::get(); // data should not have sample attribute in it.
I am also trying to achieve, any tip and suggestion?
@JenuelDev-31676163 The appends protected property is only useful if you are using serialized models (like in APIs).
If you are developping a full blade frontend, you don't need to use the appends protected property and you will always need to call these properties manually.