This doesn’t work (nothing is displayed):
echo Auth::user()->is_admin;
This, however, works fine (the column value is displayed):
echo DB::table('users')->where('id', Auth::id())->value('is_admin');
When having just echo Auth::user()
then this is displayed:
{"id":19,"name":"peeter","email":"[email protected]","is_admin":false}
As you can see it returns all the other column values just fine but "is_admin" column value is for some reason "false", no matter what the column value or type is set in phpmyadmin.
For example this is my full code that I put in web.php to test this:
Route::get('/testing', function(){
echo Auth::user()->is_admin;
echo DB::table('users')->where('id', auth::id())->value('is_admin');
});
I expected echo Auth::user()->is_admin;
or echo Auth::user()
to return the value of the "is_admin" column instead of displaying nothing or FALSE.
EDIT:
Thanks for the comments below, var_dump()
helped to verify that it always sees it as boolean and the value is always false, even though in phpmyadmin it shows different value and no matter what data type I change it to, var_dump()
always shows bool(false)
.
I just added another column in phpmyadmin and it sees the correct value now, however it sees it as integer, not a boolean. So I guess it must be a mysql bug.
DIGGING DEEPER INTO THE RABBIT HOLE:
When I renamed the old column and change the new column name to "is_admin" then new one doesn’t work anymore and old one works. So it seems like the issue is the column name! Works fine when I rename the column to anything else other than "is_admin". Very strange!
EDIT:
After renaming the column in phpmyadmin then var_dump()
shows that it is integer int(1), not a boolean anymore, even when I change the datatype to BOOLEAN. When I change the column name back to the old is_admin then var_dump()
shows that it is boolean again.
In User.php model, when I delete this code then everything works:
public function getIsAdminAttribute()
{
return $this->roles()->where('id', 1)->exists();
}
public function roles()
{
return $this->belongsToMany(Role::class);
}
However now it doesn’t see the column value as Boolean. It always sees it as Integer, but at least the value is updated when I change it in the database.
EDIT:
Just to be clear, unless I have deleted the code from User.php, for the user who’s ID is 1, "is_admin" column value is always bool(true), even if I change the value. For other users it’s always bool(false).
2
Answers
The
echo false
statement will not display anything, sincefalse
will be converted to an empty string. Try to change it to something like this:You could also typecast it like this:
You can read more in the PHP manual here.
After reading your question, it appears that this code will assist in your problem-solving.
Add a scope to your User model; see the Laravel documentation for additional information.
Then, you can access this as seen below.
Happy Coding!…