Laravel - Convert database integer to an associated string

﹥>﹥吖頭↗ 提交于 2019-12-09 04:30:32

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'

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