Trying to pass the user type in a condition laravel


问题 (Question)

When I grab the current user (who is a manager) like so:

$user = Auth::user()->user_role;

I then die and dump this:


This displays

string(7) "Manager"

I then want to use a conditional to check if it is a specific user:

dd($user == ("Admin" || "Superuser"));

This (for some reason) returns true:


What is the problem here?


$user = Auth::user()->user_role;




string(7) "Manager"


dd($user == ("Admin" || "Superuser"));




最佳答案 (Best Answer)

It should be written as ...

dd($user === "Admin" || $user === "Superuser");

... instead. There are two separate conditions that should be checked separately.

As about the current situation, it's... funny. See, || operator in PHP doesn't work like in JavaScript (where it returns either first operand, if it evaluates to truthy value, or the second operand without changing their types).

But it's PHP, and here the result of || operation is always a boolean value - either true or false. It's no surprise that it's true in this case, as only two string values in PHP are considered falsy - an empty string and '0'. The first operand of 'Admin' || 'Superuser' is neither, so this expression evaluates to true.

So it becomes...

dd($user == true);

Again, with proper comparison operator - === - you should've noticed the difference here. But it's ==, so it converts its operands' types before actually comparing them.

By the rules of type coercing (which are described quite nicely in the docpage), when one value of the comparison is boolean, the other always gets converted to boolean too. As $user isn't either '' or '0', it gets converted to true too.

So it finally becomes this:

dd(true === true);

Guess what's the result? )


dd($user === "Admin" || $user === "Superuser");

答案 (Answer) 2

Have you tried using type comparison (=== vs ==) or maybe just: dd(in_array($user, array("Admin", "Superuser")));?

What you're doing is basically "$user is not empty, and neither is 'admin' or 'superuser'"

你有试过使用类型比较(===VS==或者只是:dd(in_array($user, array("Admin", "Superuser"))); ?

你正在做的事情基本上是“$ user不是空的,也不是“管理”或“超级用户”

答案 (Answer) 3

("Admin" || "Superuser")

is evaluated first (parenthesis) and that equals true. What you really want is probably:

dd($user == "Admin" || $user == "Superuser");