Michael
Michael

Reputation: 113

Laravel - Convert database integer to an associated string

I have my users table with a column named status. In this column I just store a number, based off their status, 1 - admin, 2 - owner, etc. I know that I can display these values with {{ users->status }}, but only shows the stored number. How can I show the actual name instead of the stored number?

Upvotes: 1

Views: 2381

Answers (1)

Brian Dillingham
Brian Dillingham

Reputation: 9356

Use Eloquent Accessors & Mutators.

Define an array of statuses and use the status number from your database as a key to change the value in the model so that in the view {{ $users->status }} equals admin

class User extends Eloquent {

    protected $statuses = array(
        '1' => 'admin',
        '2' => 'owner'
    );

    public function getStatusAttribute($value)
    {
        return $this->statuses[$value];
    }

}
  • getStatusAttribute converts 1 to admin when retrieving a record.


You could also have a set method for when records are stored in the model.

In View {{ $user->status }} // echos 'admin'

Upvotes: 4

Related Questions