0

I have a table with 10 fields with these names: field1, field2, and so on... I want to retrieve a single registrer (wtih eloquent and ->first() ). And when i have the object (lets say $user), can I do something like this in the controller?

for ($i=1; $i<=10; $i++) {
    $field_name = 'field'.$i;
    if ($user->$field_name == 1) {
        // do something
    }
}

Or i have to call them manually?

    if ($user->field1 == 1) {
        // do something
    }
    if ($user->field2 == 1) {
        // do something
    }
    ....
Sumit Bijvani
  • 8,154
  • 17
  • 50
  • 82
  • 1
    Have you tried it? Because [it's possible](http://stackoverflow.com/questions/804850/get-php-class-property-by-string). – vstm May 30 '13 at 04:53

1 Answers1

1

As @vstm said, it's possible, here are two working examples of what you can do:

foreach($data as $key => $row) {
    $r[$row->$id] = ($abbreviation ? $row->$abbreviation.' - ' : ''). ($method ? $row->$name() : $row->$name);
}

and

if(isset($line['childs'])) 
{
    $childs = $model->$line['childs']()->get(['id'])->toArray();

    if(count($childs))
    {
        foreach($childs as $value)
        {
            $selected[] = $value['id'];
        }
    }
    else
    {
        $selected = null;                       
    }


    $line['selected'] = $selected;
}
Antonio Carlos Ribeiro
  • 86,191
  • 22
  • 213
  • 204