1

How can I look up a user by email? I thought that JTable::load would do it, but it returns a weird data shape:

$user = JTable::getInstance('User', 'JTable', array());
$user->load(array("email" => "someemail@gmail.com"));
print_r(json_encode($user))

            groups": null,
            "id": {
                "email": "someemail@gmail.com"
            },
            "name": "",
            "username": "",
            "email": "",
            ...

JTable::load works like this for Categories, however.

$cat = JTable::getInstance('Category', 'JTable', array());
$cat->load(array("title" => "some title"));

Do I have to use JFactory::getDbo()?

  • I assume that you have tested your code using both existing and non-existing email addresses? I would kind of expect to see a bunch of null and empty values if I searched for a non-existent user. – mickmackusa Jul 20 '18 at 6:57
  • yes, I've tested with both. They both return the same result. – steel Jul 20 '18 at 14:54
3

Joomla\CMS\Table\User::load() can only load rows by user ID. Use database query to get user ID by email and pass it to table's load() method:

$db = JFactory::getDbo();
$query = $db->getQuery(true)
    ->select($db->quoteName('id'))
    ->from($db->quoteName('#__users'))
    ->where($db->quoteName('email') . ' = ' . $db->quote($email));
$db->setQuery($query);

if ($id = $db->loadResult())
{
    $user = JTable::getInstance('User', 'JTable', array());
    $user->load($id);
}
else
{
    // User with specified $email not found.
}

If you don't intend changing user data in the table, you can use JFactory::getUser() instead:

if ($id = $db->loadResult())
{
    $user = JFactory::getUser($id);
}
  • ...but can this be done with JTable::load? – mickmackusa Jul 20 '18 at 6:45
  • Yes, exactly same way. Get user ID and pass it to JTable::load(). – Sharky Jul 20 '18 at 7:12
  • 1
    I mean, can it be done without the JFactory::getDbo()? This is the question. – mickmackusa Jul 20 '18 at 7:14
  • As far as I can tell, no. Unlike Joomla\CMS\Table::load(), Joomla\CMS\Table\User::load() can only load row by user ID instead of multiple column/value pairs. – Sharky Jul 20 '18 at 7:22
  • This is relevant to the question and your answer. Please edit this knowledge into your answer to make it more complete (upvote worthy). ...I don't know if what you are saying is true -- just trying to improve page content and put the full story in one place. – mickmackusa Jul 20 '18 at 7:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.