Correct use of accessories in Laravel
I am new to Laravel and am building a simple CRUD app to learn more about framework. I am wondering how to use accessors correctly.
I thought that accessors would be good for formatting model properties to display in a view, similar to a filter in Angular. I currently have a couple of accessories designed to convert char (1) fields to full values โโin view, like "c" for cash or "f" for funding. Is this the intended (or acceptable) use of the accessories? If so, what is a good way to prevent accessors from accessing formatting properties bound to a form, such as in an edit path.
For example, I am storing the monetary amount in db as decimal, but formatting it with characters ($ 150.00) to display in the display route. How can I prevent an accessory from changing its value when filling out an edit form? (Validation will fail because the input is limited to numeric values.)
source to share
It all depends on your needs. The key is that you don't need to create accessors for the actual columns / properties. For example, suppose assuyme has a price field in the database.
Using the following code:
$model = Model::find(1);
echo $model->price;
You can only display row price to display data from the database.
But you can also create an accessor for a more advanced property:
public function getCurPriceAttribute($value)
{
return '$ '.($this->price * 1.08); // for example adding VAT tax + displaying currency
}
now you can use:
$model = Model::find(1);
echo $model->price;
echo $model->cur_price;
Now, if you want to put data into a form, you will use $model->price
to allow the user to change it without currency, and in other places where you want to display the value of the product in currency, you will use$model->cur_price
source to share