Answer the question
In order to leave comments, you need to log in
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);
});
{{Form::model($tariff, ['method' => 'PATCH', 'route' => ['tariffs.update', $tariff->id]])}}
{{ Form::text('salary', null, ['class' => 'form-control']) }}
{{Form::close()}}
public function getSalaryAttribute() {
return formatRubles($this->attributes['salary']);
}
public function salary() {
return $this->attributes['salary'];
}
Answer the question
In order to leave comments, you need to log in
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()}}
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 questionAsk a Question
731 491 924 answers to any question