Search code examples
phplithium

Lithium Auth::check user with relationships, relational database


I am using Auth::check('user', $this->request), where 'user' is the name of my Auth::config configuration, to successfully authenticate and login users against a Users table. Upon successful user login, the user information is stored in the session and can be accessed via Auth::check('user').

I have a relational design in place where the Users table has a many-to-one relationship with a table named Sites. When Auth::check queries the Users table to authenticate a user logging in, it only returns information from the Users table. I need Auth:check to return the User with its related data from the Sites table. Both the User and Site models have the appropriate hasOne and hasMany relationships defined. How can I ensure that the user is queried and returned with its corresponding related data via Auth::check()?


Solution

  • While it's generally inadvisable to store more session information than is absolutely necessary, it's possible to do this through the 'query' configuration key of the Form auth adapter. Just create a wrapper method in your Users model that can take a query configuration array, and return a user object with associated relationships. Probably something like this:

    public static function authenticate (array $query) {
        return static::all($query + array('with' => 'Sites'));
    }
    

    Then, add 'query' => 'authenticate' to your 'user' auth configuration.