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);
}
...