'Convert database integer to an associated string in Laravel?
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.
Solution 1:[1]
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 }}
Solution 2:[2]
You can use something like enum casting. Please take a look and see if this works for you ;)
Solution 3:[3]
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');
?>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rouhollah Mazarei |
| Solution 2 | knubbe |
| Solution 3 |
