Trying to pass the user type in a condition laravel

试图通过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:

dd($user);

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:

bool(true)

What is the problem here?

当我抓住当前用户(经理)一样:

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

我死后,把这个:

dd($user);

这将显示

string(7) "Manager"

然后我想用一个条件来检查是否一个特定的用户:

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

这返回true(由于某种原因):

bool(true)

这里的问题是什么?

最佳答案 (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");

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/16925928