Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mlusas's avatar

Session specific variables in EagerLoad methods

I'm trying to create an Eagerload that would be specific to a specific user (whether they liked a model via a character_likes pivot table), and I am having difficulty sending sending the user_id to the EagerLoad Model Method liked().

Can someone share the best practice for doing this?

Here is some of my code:

ApiController

    $data = filter_var_array($request->all(), FILTER_SANITIZE_STRING);
        $userId = $request->header('X-User');

        $eagerLoads = [
            "liked"
        ];

    /** I tried using this method, but we have a lot of models that we check, with a variety of optional includes, and would cause a lot of issues when we run code updates
        * $eagerLoads["followed"]  = function($query) use ($binaryUserId){
        *    $query->where('user_id', '=', $binaryUserId);
        *};
    */

        $charsInst = Character::with($eagerLoads);

        if( !empty($data['with_trashed']) ){
            $charsInst->withTrashed();
        }
        $characters = $charsInst->get();

CharacterModel

...

    public function followed(){
        // I would like to be able to do this commented line rather than the uncommented line:
        // return $this->hasOne('FollowCharacter', 'character_id', 'id')->where('user_id', '=', $userId);
            return $this->hasOne('FollowCharacter', 'character_id', 'id');
        }
    
...
0 likes
1 reply
mlusas's avatar
mlusas
OP
Best Answer
Level 4

I'm not sure if this is the best solution, but I'm simply using PHP constants. It feels like a hack, but is there a better practice?

Here is the revised code:

ApiController

$data = filter_var_array($request->all(), FILTER_SANITIZE_STRING);
        $userId = $request->header('X-User');
    define('USER_ID', $userId);

        $eagerLoads = [
            "liked"
        ];

    /** I tried using this method, but we have a lot of models that we check, with a variety of optional includes, and would cause a lot of issues when we run code updates
        * $eagerLoads["followed"]  = function($query) use ($binaryUserId){
        *    $query->where('user_id', '=', $binaryUserId);
        *};
    */

        $charsInst = Character::with($eagerLoads);

        if( !empty($data['with_trashed']) ){
            $charsInst->withTrashed();
        }
        $characters = $charsInst->get();

CharacterModel

...

    public function followed(){
            return $this->hasOne('FollowCharacter', 'character_id', 'id')->where('user_id', '=', USER_ID);
        }
    
...

Please or to participate in this conversation.