Search code examples
laraveleloquenteloquent-relationship

Laravel With Sum Function Call to undefined method


Laravel 8 with latest updates

Customer has many machines and machines has many accounts records

This work {{ machines.accounts }}

Route::get('/', function () {
    return Customer::with([
        'machines',
        'machines.accounts',
        'user'
    ])
        ->get();
});

But withSum() or withCount() doesn't work

Route::get('/', function () {
    return Customer::with([
        'machines',
        'user'
    ])
        ->withSum('machines.accounts', 'credit')
        ->get();
});

Error: Call to undefined method App\Models\Customer::machines.accounts()


Solution

  • Using with('machines', callback) and inside add withSum()