Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper Use of Accessors in Laravel

I am new to Laravel and am building a simple CRUD app to learn more about the framework. I am curious about the proper use of accessors.

I thought accessors would be great for formatting a model's properties for display in a view, much like a filter in Angular. Currently I have a few accessors set to convert char(1) fields to full values in the view, like "c" to cash or "f" to financed. Is this the intended (or an acceptable) use of accessors? If so, what is a good way to prevent accessors from formatting properties that are binded to a form, for instance, in the edit route.

For example, I am storing a monetary amount in the db as a decimal but formatting it with characters ($150,00) for display in the show route. How can I prevent the accessor from altering the value when populating the edit form? (Validation will fail as the input is limited to numeric values).

http://laravel.com/docs/4.2/eloquent#accessors-and-mutators

http://laravel.com/docs/4.2/html#form-model-binding

like image 890
Kelly Kiernan Avatar asked Dec 14 '22 19:12

Kelly Kiernan


1 Answers

Everything depends on your needs. The key is that you don't need to create accessors to actual columns/properties. For example let's assuyme in DB you have price field.

Using the following code:

$model = Model::find(1);
echo $model->price;

You can display row price just to display data from database.

But you can also create accessor for unexisting 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 form you will use $model->price to allow user to change it without currency and in other places where you want to display product value with currency you will use $model->cur_price

like image 199
Marcin Nabiałek Avatar answered Mar 06 '23 01:03

Marcin Nabiałek