Refactoring a php function at Laravel Model

I have a method at a Model like this:

public function questionOwner($id)
    {
        if (auth()->user()->id == $id) {
           return true;
        }else{
            return false;
        }
    }

Now I wanted to refactor this function so I tried this:

public function queOwner($id)
    {
        return !! auth()->user()->id == $id;
    }

So if auth()->user()->id was not equals to $id, then it should return false because of !! but I don’t know why it always return TRUE!

So if you know what’s going wrong here and how can I refactor this function, please let me know, thanks…

>Solution :

The problem with your refactored function queOwner() is that the !! operator is not doing what you think it is doing. The !! operator is called the "double negation" operator, and it’s commonly used to convert a truthy or falsy value to a boolean value (i.e., true or false). However, in this case, it’s not working as expected because of operator precedence.

In your refactored function, the == operator has higher precedence than the !! operator. So the expression auth()->user()->id == $id is evaluated first, and it returns a boolean value (true or false) depending on whether the user ID matches the given ID. Then the !! operator is applied to the boolean value, which simply returns the same boolean value. So the final result is a boolean value, not the expected true or false string.

To fix this issue, you can use parentheses to group the comparison expression before applying the !! operator:

public function queOwner($id)
{
return !! (auth()->user()->id == $id);
}

With this change, the comparison expression is evaluated first, and its result is grouped by parentheses before being converted to a boolean value by the !! operator. The final result will be a boolean value (true or false) as expected.

Alternatively, you can simplify the function using the === operator, which checks for value and type equality:

public function queOwner($id)
{
return auth()->user()->id === $id;
}

This will return true if the user ID is equal to the given ID, and false otherwise.

Leave a Reply