Odinovsky Odinovsky - 7 months ago 42
PHP Question

Laravel - Multiple query function to multiple eager loaded relationships

I'm wondering if there's a solution to a multiple closure loading two hasOne relationships. With one relationship (personaldata) I only needed some columns, and second relationship (userfile) having a where clause.
It works if I either remove the select from personaldata or remove the where clause from userfile, otherwise having two closures renders one of them with null value.

$user = Users::with(['personaldata' => function($a) {
$a->select('first_name', 'title_name', 'last_name', 'street_address', 'city', 'state', 'country_code', 'zip_code', 'telephone_data', 'skype', 'per_street_address', 'per_city', 'per_state', 'per_country_code', 'per_zip_code');
'userfile' => function($b) {
$b->where('type', '1');
->where('user_id', Auth::id())

Answer Source

change your code like this :

$user = Users::with(['personaldata' => function($query) {
            $query->select('first_name', 'title_name', 'last_name', 'street_address', 'city', 'state', 'country_code', 'zip_code', 'telephone_data', 'skype', 'per_street_address', 'per_city', 'per_state', 'per_country_code', 'per_zip_code');
        ->with(['userfile' => function($query) {
            $query->where('type', '1');
        ->where('user_id', Auth::id())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download