Jump to content

$users->get doesn't return null ?


Doc
 Share

Recommended Posts

Hi,

How do you check if a user exists or not ?

I'm using this code :

$item = $users->get("email=example@processwire.com");
echo $item->name;

but whatever the email exists or not, I never get null in $item.

I also tried :

if ($item) {
    case 1
else
	case 2

and case 1 always wins.

Do I have to check $item->id then ?

Thanks

Link to comment
Share on other sites

$Item will return an Object whether or not a user was found, hence case 1 will always be true. So, yes, you need to check differently. I like to check for both the object and an ID. Sometimes if you check only ID you might get a PHP error about a 'call to member function on a non-object' blah blah..:

$item = $users->get("email=example@processwire.com");
if($item && $item->id) echo $item->name;
else echo 'No user found';

 

Edited by kongondo
  • Like 3
Link to comment
Share on other sites

Just like $pages->get, $users->get returns a NullPage object if no match was found. Thus, you can check for that. I feel that doing it this way is better for readability (implicitly illustrating the difference between a new User object with no id and the result of a get call with no match), but that may just be a personal preference.

$item = $users->get("email=example@processwire.com");
if($item instanceof NullPage) {
	// Not found
} else {
	// Do something
}

 

  • Like 4
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...