Home > Software design >  Convert database integer to an associated string in Laravel?
Convert database integer to an associated string in Laravel?

Time:04-12

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? And I don't use model here.

CodePudding user response:

You can use something like enum casting. Please take a look and see if this works for you ;)

CodePudding user response:

You can define an accessor in your User model:

public function getStatusStringAttribute()
{
    switch ($this->status) {
        case 1:
            return "Admin";
            break;
        case 2:
            return "Owner";
            break;
    }
}

and get this attribute like this:

{{ $user->statusString }}

CodePudding user response:

You should create a table with user's name role and then join 2 tables. For example: You have 1 table named users with column status. You need to create a table for example user_status_name. id 1 -- name admin, id 2 -- name user

<?php
$users = User::join('user_status_name', 'user_status_name.id', '=', 'users.status')->pluck('name');
?>
  • Related