Laravel - manipulate data from a model

Perhaps I am complicating this too much or missing something very simple, so forgive me if I am.

I am trying to manipulate / display some data in my model.

A very simple example of what I'm trying to do:

I have $model->attrthis, it will return everything that is in my database for this column.

I know there will be a refund 1, 2or 3.

When displayed in the presentation, I would like to see this value indicates something else, for the sake of this example, you can say 1=>'red', 2=>'blue', 3=>'green'.

How will I do this in the model? I looked at Accessors and Mutators, but I'm not sure if they are the right thing.

Thanks in advance.

+4
source share
2 answers

You will need accessor :

public function getNewValueAttribute($value){
    switch($value) {
        case '1':
            return 'red';
        case '2':
            return 'blue';
        case '3':
            return 'green';
    }
}

Put this inside your model and it should work just fine!

Laravel converts the attribute to CamelCase, so it $user->full_namehas an accessor getFullNameAttribute, $user->all_your_base_are_belong_to_usbecomes getAllYourBaseAreBelongToUsAttribute.

+3
source

I think you are trying to output text based on conditions. If you can try it

@if($model->attr==1)
  red
@elseif($model->attr==2)
  blue
@else
  green
@endif
0
source

Source: https://habr.com/ru/post/1675036/


All Articles