Two laravel relationships on the same call

Laravel allows you to chain relationships. In your case, you want to include the users relationship on your UserContract model, and the nonAcceptedContracts relationship on your User model. Simply use dot (.) notation on the relationships:

return UserContract::with([
  'contracttax',
  'contractproperty',
  'persons',
  'contractwarranty',
  'users.nonAcceptedContracts', // Note: This will include both `users` and `nonAcceptedContracts`
  'contracts',
  'tags'
])->orderBy('created_at', 'desc')
->get();

Now, when iterating your UserContract results, you can access users and nonAcceptedContracts:

foreach ($userContracts as $userContract) {
  foreach ($userContract->users as $user) {
    // Do something with `$user->nonAcceptedContracts` ...
  }
}

See https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading for full information

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top