M
M
miki1312014-10-31 16:17:04
Laravel
miki131, 2014-10-31 16:17:04

How to separate model attributes for a view and for other uses?

I have Tariff model for such table

Schema::create('tariffs', function(Blueprint $table) {
  $table->increments('id');
  $table->string('title');
  $table->integer('salary')->unsigned()->default(0);
});

The salary field is responsible for the salary and can be with a penny and I store it in the database as an integer (multiply by 100)
I have a view
{{Form::model($tariff, ['method' => 'PATCH', 'route' => ['tariffs.update', $tariff->id]])}}
  {{ Form::text('salary', null, ['class' => 'form-control']) }}
{{Form::close()}}

In it, the user enters the amount with kopecks.
In order for the view to show the amount in the form of "10.45 rubles" I did
public function getSalaryAttribute() {
  return formatRubles($this->attributes['salary']);
}

But now a simple call to the salary attribute of the Tariff model object returns the formatted value to me.
I made a method, but I think this output is ugly
public function salary() {
  return $this->attributes['salary'];
}

Are there other solutions to my problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
miki131, 2014-10-31
@miki131

I thought, thought, and ... in order not to throw unrelated things such as formatRubles into the model, I need to put everything in the view, it turned out like this

{{Form::model($tariff, ['method' => 'PATCH', 'route' => ['tariffs.update', $tariff->id]])}}
  {{ Form::text('salary', isset($tariff) ? formatRubles($tariff->salary) : null, ['class' => 'form-control']) }}
{{Form::close()}}

I think the maximum that can be expanded in this situation is to expand the possibilities of the Form Model Binding for automatic checks isset($tariff)

A
ajaxtelamonid, 2014-10-31
@ajaxtelamonid

That really shouldn't be done. The model should give clean data, and for display in views, use additional functions. Remove getSalaryAttribute() and make a displaySalaryInRoubles() method in the model for use in views, where you format the sum however you want.
If for ideological reasons you do not want to load the ActiveRecord model with unnecessary methods, do it through such a presenter, for example - https://github.com/laracasts/Presenter . Will be $object->present()->displaySalary . Although I would do the first option.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question