Laravel - Convert database integer to an associated string

老子叫甜甜 提交于 2019-12-08 03:47:42

问题


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?


回答1:


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'



来源:https://stackoverflow.com/questions/26105981/laravel-convert-database-integer-to-an-associated-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!