redrom
redrom

Reputation: 11632

CakePhp how to get data from model in custom compoment?

I would like to get user object by his ID in the custom component. I tried to do by this way:

$query = $this->Users->find('all', [
            'conditions' => [
                'Users.id' => $uid,
                'Users.state' => 'ACTIVE'
            ]
        ]);
$results = $query->first();

But i got the following error because the Users model is null

Call to a member function find() on null 

Is possible to get these data from the table (model) in the custom component please and how?

Many thanks for any advice.

Upvotes: 0

Views: 103

Answers (1)

Jacek B Budzynski
Jacek B Budzynski

Reputation: 1413

How about this:

<?php
namespace App\Controller\Component;

use Cake\Controller\Component;
use Cake\Controller\ComponentRegistry;
use Cake\Network\Exception\InternalErrorException;
use Cake\Utility\Text;

use Cake\ORM\TableRegistry; // <----


class YourComponent extends Component
{
    public function getUser($id = null)
    {
        $this -> Users = TableRegistry::get('Users'); // <----

        $user = $this -> Users -> find()
            -> where(['state' => 'ACTIVE', 'id' => $id])
            -> first();

        return $user;
    }

}

Upvotes: 1

Related Questions